如何继承python生成器并重写__

2024-04-19 17:28:10 发布

您现在位置: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 super(Mother, self):
TypeError: 'super' object is not iterable

我想这只是关于语法的问题,我试图不使用任何方法调用super(Mother,self),只调用对象本身。 代码如下:

^{pr2}$

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


Tags: inpytestself信息mostforline
1条回答
网友
1楼 · 发布于 2024-04-19 17:28:10

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))本身就是super类型的对象,它没有任何特殊的方法。在

演示:

^{pr2}$

相关问题 更多 >