我想打电话给母班,但我得到这样的信息:
Traceback (most recent call last):
File "***test.py",line 23,in
我认为这只是语法,我试着在没有任何方法的情况下调用超级(母亲,自己),只是对象本身.
这里的代码:
class Mother(object):
def __init__(self,upperBound):
self.upperBound = upperBound
def __iter__(self):
for i in range (self.upperBound):
yield i
class Daughter(Mother):
def __init__(self,multiplier,upperBound):
self.multiplier = multiplier
super(Daughter,self).__init__(upperBound)
def __iter__(self):
for i in super(Mother,self): # Here
yield i * self.multiplier
daughter = Daughter(2,4)
for i in daughter:
print i
最佳答案
super()返回的代理对象不可迭代,因为MRO中有__iter__方法.你需要明确地查找这些方法,因为这只是搜索的一部分:
for i in super(Daughter,self).__iter__():
yield i * self.multiplier
请注意,您需要在当前类上使用super(),而不是父类.
super()不能直接支持特殊方法,因为这些方法是由Python直接在类型上查找的,而不是实例.见Special method lookup for new-style classes:
For new-style classes,implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type,not in the object’s instance dictionary.
type(super(Daughter,self))是超类型对象本身,它没有任何特殊方法.
演示:
>>> class Mother(object):
... def __init__(self,upperBound):
... self.upperBound = upperBound
... def __iter__(self):
... for i in range (self.upperBound):
... yield i
...
>>> class Daughter(Mother):
... def __init__(self,upperBound):
... self.multiplier = multiplier
... super(Daughter,self).__init__(upperBound)
... def __iter__(self):
... for i in super(Daughter,self).__iter__():
... yield i * self.multiplier
...
>>> daughter = Daughter(2,4)
>>> for i in daughter:
... print i
...
0
2
4
6