python - 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
解决方案
事实证明,元类是可能的。
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 为我指明了正确的方向。
推荐阅读
- javascript - 如何在通过 Adonis Lucid ORM 模型创建记录时生成 UUID?
- db2 - 从表 A(变量)问题中选择 *
- ios - 如何检查用户是否在 Swift 中登录了 Google 帐户?
- mysql - 用条件合并多个表
- html - 如何将文本输入字段中的字符数限制为 html 中的最多 10 个字符?
- inno-setup - 如何检查文件是否存在并要求在 Pascal 脚本代码中覆盖
- javascript - React Redux TypeError:传播不可迭代实例的无效尝试
- r - 删除前 n 个单词并计数
- ms-access - 如何在 ms 访问中编写一个将运行 sql 的宏
- mysql - 如何通过添加现有表列将扩展表添加到现有表