您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:21:56 python 字数 4296 阅读 511 来源 www.jb51.cc/python

我想打电话给母班,但我得到这样的信息: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

概述

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

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(),而不是父类.

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__所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶