首页 > 解决方案 > Is it possible to make a class object iterable in Python?

问题描述

I'm wondering if it's possible to make a class object iterable in Python (ie. a subclass of type, NOT an instance of a class).

I've tried the following code:

class Foo:
    @classmethod
    def __iter__(cls):
        yield 1


print(next(Foo.__iter__()))  # prints 1
print(next(iter(Foo)))  # TypeError: 'type' object is not iterable

标签: pythonpython-3.x

解决方案


事实证明,元类是可能的。

class Foo(type):
    def __iter__(self):
        yield self.baz


class Bar(metaclass=Foo):
    baz = 1


print(type(Bar))  # prints "<class '__main__.Foo'>"
print(next(Bar.__iter__()))  # prints "1"
print(next(iter(Bar)))  # prints "1"

感谢@DanielB 为我指明了正确的方向。


推荐阅读