Python中的继承;TypeError:run()不接受任何参数(给定2个)";

Python中的继承;TypeError:run()不接受任何参数(给定2个)";,python,inheritance,overwrite,Python,Inheritance,Overwrite,我看到了其他类似的主题,但不是我真正需要的 我有一个名为“Base”的类,其中调用了几个方法。最后是它自己的“运行”: 我有另一个类,叫做“BaseComp”,它用特定于给定需求的方法扩展了“Base”,在它上面有一个“run”方法,必须重写,最后是类本身的“run”: import dummy.io as cpio class BaseComp(Base): def __init__(self, cpio): Base.__init__(self, cpio)

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

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

我有另一个类,叫做“BaseComp”,它用特定于给定需求的方法扩展了“Base”,在它上面有一个“run”方法,必须重写,最后是类本身的“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)”的调用

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)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/home/user/components/comp1/_init__uuu.py”,第166行,运行component.start()中
文件“/home/user/directory/apps/Base.py”,第58行,在start self.run(debug)中****这是在start方法中
TypeError:run()不接受任何参数(给定2个)
我不知道是什么原因导致了这个错误。我相信这可能与调用了这么多“run”方法有关

这让我抓狂,因为我在整个继承模式中有点迷失了

任何帮助都会很好


thks

首先,你不能有这个

class SomeClass(object):
   def somefunc():
      print 'somefunc in SomeClass'
因为python类方法默认接收“self”。 尝试从类实例调用somefunc将产生

TypeError: somefunc() takes no arguments (1 given)
您可以添加self

class SomeClass(object):
   def somefunc(self):
      print 'somefunc in SomeClass'
或者,如果您不需要或不想要“self”,您可以将其设置为顶级函数(而不是类函数)或静态方法

class SomeClass(object):
   @staticmethod
   def somefunc():
      print 'somefunc in SomeClass'

这就是BaseComponent类的run方法。

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


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

从错误打印输出中,您似乎正在调用OSUtils(??)中定义的run()方法。正如Wyrmwood提到的,BaseComponent类中定义的run方法应该具有自参数或@staticmethod decorator


那么
Base
在哪里呢?这里有一个
BaseComponent
。您发布的代码不足以重现您的问题(它不会显示问题,因为您所有的
run()
方法都有
self
debug
参数)。你确定你没有遗漏某个组件,或者在
运行
函数的缩进中出错吗?这应该是某种线程吗?你是对的,Martijn。很抱歉输入错误。顶部的第一个类称为“Base”,而不是“BaseComponent”
class SomeClass(object):
   def somefunc(self):
      print 'somefunc in SomeClass'
class SomeClass(object):
   @staticmethod
   def somefunc():
      print 'somefunc in SomeClass'
class BaseComponent(OSUtils):
    def run(self, debug=False):
        ...
class BaseComponent(OSUtils):
    @staticmethod
    def run(debug=False):
        ...