相关疑难解决方法(0)

构建一个基本的Python迭代器

如何在python中创建迭代函数(或迭代器对象)?

python iterator object

545
推荐指数
8
解决办法
34万
查看次数

猴子修补方法覆盖

我试图弄清楚为什么以下示例不起作用。

class BaseClass(object):
    def __init__(self):
        self.count = 1

    def __iter__(self):
        return self

    def next(self):
        if self.count:
            self.count -= 1
            return self
        else:
            raise StopIteration


class DerivedNO(BaseClass):
    pass


class DerivedO(BaseClass):
    def __init__(self):
        self.new_count = 2
        self.next = self.new_next

    def new_next(self):
        if self.new_count:
            self.new_count -= 1
            return None
        else:
            raise StopIteration


x = DerivedNO()
y = DerivedO()

print x
print list(x)
print y
print list(y)
Run Code Online (Sandbox Code Playgroud)

这是输出:

<__main__.DerivedNO object at 0x7fb2af7d1c90>
[<__main__.DerivedNO object at 0x7fb2af7d1c90>]
<__main__.DerivedO object at 0x7fb2af7d1d10>
Traceback (most recent call …
Run Code Online (Sandbox Code Playgroud)

python inheritance overriding

3
推荐指数
1
解决办法
1630
查看次数

标签 统计

python ×2

inheritance ×1

iterator ×1

object ×1

overriding ×1