我有四个不同的类(class)。有一个主基/父类,两个从该父类继承的主类,以及另一个从这两个主类继承的类。如果我有一个与父类同名但参数数量不同的方法,我会收到 TypeError。
# Example
class Parent(object):
def check(self, arg):
tmp = {
'one': False,
'two': False
}
try:
if 'one' in arg:
tmp['one'] = True
if 'two' in arg:
tmp['two'] = True
except TypeError:
pass
return tmp
class Child(Parent):
def check(self, arg):
return Parent.check(self, arg)['one']
def method(self, arg):
if self.check(arg):
print 'One!'
class ChildTwo(Parent):
def check(self, arg):
return Parent.check(self, arg)['two']
def method(self, arg):
if self.check(arg):
print 'Two!'
class ChildThree(Child, ChildTwo):
def check(self, arg, arg2):
print arg2
return Child.check(self, arg)
def method(self, arg):
if self.check(arg, 'test'):
print 'One!'
ChildTwo.method(self, arg)
test = ChildThree()
test = test.method('one and two')
runfile('untitled6.py', wdir='./Documents')
test
One!
Traceback (most recent call last):
File "< stdin >", line 1, in < module >
File "C:\Users\py\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\py\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "untitled6.py", line 49, in
test = test.method('one and two')
File "untitled6.py", line 46, in method
ChildTwo.method(self, arg)
File "untitled6.py", line 34, in method
if self.check(arg):TypeError: check() takes exactly 3 arguments (2 given)
但是,当我从“ChildThree”中的“check”方法中删除第二个参数时,它似乎工作正常:
class ChildThree(Child, ChildTwo):
def check(self, arg):
return Child.check(self, arg)
def method(self, arg):
if self.check(arg):
print 'One!'
ChildTwo.method(self, arg)
runfile('untitled6.py', wdir='./Documents')
One!
Two!
我对类/继承相当陌生,所以我不确定为什么额外的参数会导致 TypeError,即使它使用单个参数调用父类方法。
最佳答案
考虑这一行:
ChildTwo.method(self, arg)
您显式传入了 self
。这里的 self
是对 ChildThree
实例的引用。随后,在 ChildTwo.method
的主体中:
if self.check(arg):
这与我们在这里讨论的self
是一样的; self
仍然是您的 ChildThree
实例的引用。
看起来您期望 self
做一些神奇的事情,但事实并非如此 - 它只是一个普通的旧名称。为了让它引用 ChildTwo
实例,它必须像绑定(bind)方法一样被调用。比较和对比:
my_child_two.method(arg)
<-- “self”通过描述符协议(protocol)隐式传递ChildTwo.method(self, arg)
<-- “self”就是任何它本身
关于python - 具有相同方法名称但不同参数的多重继承会导致类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497656/