是否可以为类定义__iter__方法?

时间:2018-03-22 02:03:57

标签: python python-3.x iterator

假设我们有以下类:

class Klass:
    iterable_attr_names = {'x', 'y', 'z'}
    x = 5
    y = 6
    z = 7
    def __init__(self):
        pass
    def foo(*args): # 'foo' is not in iterable_attr_names
        return

是否可以为类定义__iter__方法,而不仅仅是类的实例?类__iter__方法的实现可能如下所示:

class KlassIter:
    def __init__(self, klass):
        self._klass = klass
        self._inner_it = iter(klass.iterable_attr_names)
    def __next__(self):
        attr_name = next(self._inner_it)
        return getattr(self._klass, attr_name)

然后我们可以这样做:

print(Klass.x)
print(Klass.y)
print(Klass.z)

和此:

for attr in Klass:
    print(attr)

0 个答案:

没有答案