概述
我想打电话给母班,但我得到这样的信息:
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
这只是一个例子,我的目的是读取文件并逐行屈服.然后子类生成器解析所有行(例如,从行中生成一个列表…).
for i in super(Daughter,self).__iter__():
yield i * self.multiplier
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
总结
以上是编程之家为你收集整理的如何继承python生成器并覆盖__iter__全部内容,希望文章能够帮你解决如何继承python生成器并覆盖__iter__所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧