gpt4 book ai didi

python - 迭代一个类型而不实例化它

转载 作者:行者123 更新时间:2023-12-03 23:05:53 24 4
gpt4 key购买 nike

问题
我希望能够在不实例化类型的情况下迭代它,类似于枚举。

class Foo:
"""Class I want to iterate over without instantiating."""
ALLOWED_VALUES = (1, 2, 3)

# I want iterating over `Foo` to be equivalent to iterating over `Foo.ALLOWED_VALUES`
for val_from_tuple, val_from_foo in zip(Foo.ALLOWED_VALUES, Foo):
assert val_from_tuple == val_from_foo
这种行为对于枚举是可能的,但前提是 ALLOWED_VALUES是有效的 python 名称。我希望在没有此限制的情况下具有相同的迭代行为。
我试过的
我尝试实现 __iter__()作为 staticmethodFoo这样一个 Foo 的实例不需要获得 Iterator为了它。这允许我迭代 Foo.__iter__() ,但是 iter(Foo)引发错误。这似乎是因为 iter(Foo)寻找 __iter__方法在 type ,不在 Foo (因为 Foo 是一个 type 对象)。
class Foo:
"""Class I want to iterate over without instantiating."""
ALLOWED_VALUES = (1, 2, 3)

@staticmethod
def __iter__():
return Foo.ALLOWED_VALUES

# This works, but isn't what I want because it involves calling `__iter__()` explicitly.
for val in Foo.__iter__():
print(val)

# This raises an error:
# `TypeError: 'type' object is not iterable`
for val in Foo:
print(val)

最佳答案

Enum是可迭代的,因为它使用不同的元类( EnumMeta 而不是 type )来创建它。您可以定义自己的元类来提供 __iter__ 的定义。其中type本身缺乏。

class IterableClass(type):
def __iter__(self):
yield from self.ALLOWED_VALUES

class Foo(metaclass=IterableClass):
ALLOWED_VALUES = (1,2,3)

for x, y in zip(Foo.ALLOWED_VALUES, Foo):
assert x == y

关于python - 迭代一个类型而不实例化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62762435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com