如何继承python生成器并覆盖__iter __

时间:2016-06-06 08:25:27

标签: python inheritance generator

我想打电话给母班,但我收到了这条消息:

Traceback (most recent call last):
  File "***test.py", line 23, in <module>
    for i in daughter:
  File "***test.py", line 18, in __iter__
    for i in super(Mother, self):
TypeError: 'super' object is not iterable

我认为这只是语法问题,我尝试在没有任何方法的情况下调用 super(母亲,自我),只是对象本身。 代码如下:

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

这里只是一个例子,我的目的是读取一个文件并逐行屈服。然后子类生成器解析所有行(例如,从行中生成一个列表...)。

1 个答案:

答案 0 :(得分:3)

super()返回的代理对象不可迭代,因为MRO中有__iter__方法。您需要查找显式这样的方法,因为这只是搜索的一部分:

for i in super(Daughter, self).__iter__():
    yield i * self.multiplier

请注意,您需要在当前类上使用super(),而不是父级。

super()无法直接支持特殊方法,因为这些方法是由Python直接在类型上查找的,而不是实例。见Special method lookup for new-style classes

  

对于新式类,只保证在对象的类型上定义特殊方法的隐式调用才能正常工作,而不是在对象的实例字典中。

type(super(Daughter, self))super类型对象本身,它没有任何特殊方法。

演示:

>>> 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(Daughter, self).__iter__():
...             yield i * self.multiplier
...
>>> daughter = Daughter(2, 4)
>>> for i in daughter:
...     print i
...
0
2
4
6