如何继承python生成器并覆盖__iter__

前端之家收集整理的这篇文章主要介绍了如何继承python生成器并覆盖__iter__前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想打电话给母班,但我得到这样的信息:

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
原文链接:https://www.f2er.com/python/438567.html

猜你在找的Python相关文章