gpt4 book ai didi

python - Python中的继承: "TypeError: run() takes no arguments (2 given)"

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:14 24 4
gpt4 key购买 nike

我看到了与此类似的其他主题,但不是我真正需要的。

我有一个名为“Base”的类,其中调用了多种方法。最后是它自己的“运行”:

class BaseComponent(OSUtils):

def __init__(self, cpio):
OSUtils.__init__(self, cpio.logger)
self.io = cpio

def debug(self, msg):
print("[Debug] %s" % msg)
self.logger.debug(msg)

def start(self, debug=False):

try:
self.info("--- Running %s:" % self.__class__.__name__)
print self.__class__.__name__
self.run(debug)

def run(debug=False):
component = BaseComp(cpio.ComponentIO())
component.start(debug)

if __name__ == '__main__':
print ("Testing")

我有另一个类,称为“BaseComp”,它使用特定于给定需求的方法扩展“Base”,其中有一个必须重写的“run”方法,在其末尾是类本身:

import dummy.io as cpio
class BaseComp(Base):

def __init__(self, cpio):
Base.__init__(self, cpio)
self.io = cpio

def run(self, debug=False):
#this method will be rewritten latter
#no matter what goes below
#
msg="blahblahblah"
Exception(msg)

def run(debug=False):
component = BaseComp(cpio.ComponentIO())
component.start(debug)

if __name__ == '__main__':
print ("Testing")

这个类由另一个名为 Hello 的类扩展。 Hello重写了BaseComp的方法“run”,最后也有自己的“run”。在此运行中,调用了“component.start(debug)

from base_components import BaseComp
import dummy.io as cpio
class Hello(BaseComp):

def run(self, debug=True):
print "Begin"
msg="hello world"
print "End"

def run(debug=True):
component = Hello(cpio.ComponentIO())
component.start(debug)

if __name__ == '__main__':

print("Testing Start")
run(debug = True)
print("Test End")

component.start(debug)从第一个类(“Base”)调用方法start

但是,当调用此电话时,我得到

Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/user/components/comp1/__init__.py", line 166, in run component.start()
File "/home/user/directory/apps/Base.py", line 58, in start self.run(debug) ***** this is in the start method
TypeError: run() takes no arguments (2 given)

我不知道是什么原因导致了这个错误。我相信这可能与调用了如此多的“run”方法有关

这让我发疯,因为我对整个继承模式有点迷失

任何帮助都会很棒

谢谢

最佳答案

我认为你只是有一个缩进错误。在基础文件中,run 函数在类内部缩进,因此被称为 run 方法;但是它不接受自动 self 参数,因此会出现错误。

您可能会发现重命名函数很有用,这样它们就不会与方法共享名称。

关于python - Python中的继承: "TypeError: run() takes no arguments (2 given)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30355996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com