Python迭代器作为类成员?

时间:2013-11-26 10:22:37

标签: python inheritance python-2.7 iterator

我的计划如下:

class Base(object):
    param, d=0, 1
    def get_all(self):
        while True:
            a = self.get_xxx(param)
            if not a:
                break
            handle(a)
            param += d

class A(Base):
    def get_xxx(param):
        return some_method(param)

class B(Base):
    def get_xxx(param):
        return other_method(param)

然后,我被告知对于B,在每个get_xxx param之后应该是+ 1而不是param + d。这意味着我需要在get_all结尾处提取param更改逻辑。我想出了一个使用迭代器的方案:

class Base(object):
    def get_all(self):
        get_xxx = self.get_xxx()
        while True:
            a = get_xxx.next()
            if not a:
                break
            handle(a)

class A(Base):
    def get_xxx():
        param, d = 0, 1
        while True:
            yield somemethod(param)
            param += d

class B(Base):
    def get_xxx():
        param = 0
        while True:
            a = somemethod(param)
            param = a + 1
            yield a

问题解决了,但不知怎的,我觉得不舒服。所以我想知道是否有更好的解决方案?非常感谢!

1 个答案:

答案 0 :(得分:0)

我会像paramd实例属性:

class Base(object):
    def __init__(self):
        self.param = 0
        self.d = 1

然后您不必明确地将任何内容传递给get_xxx()。你可以替换

param += d

self.iterate_param(a):
Base.get_all()

然后在你的两个子类中适当地定义iterate_param(),即

class A(Base):
    ...
    def iterate_param(self, a):
        self.param += self.d

class B(Base):
    ...
    def iterate_param(self, a):
        self.param = a + 1