加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:46:50 所属栏目:Python 来源:网络整理
导读:我想打电话给母班,但我得到这样的信息: Traceback (most recent call last): File "***test.py",line 23,in 我认为这只是语法,我试着在没有任何方法的情况下调用超级(母亲,自己),只是对象本身. 这里的代码: class Mother(object): def __init__(self,upper

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读