迭代类型而不实例化它

2024-04-25 06:10:52 发布

您现在位置:Python中文网/ 问答频道 /正文

问题

我希望能够在不实例化类型的情况下对其进行迭代,类似于枚举

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__()实现为Foo上的staticmethod,这样就不需要Foo的实例来获取Iterator。这允许我在Foo.__iter__()上迭代,但是iter(Foo)会引发错误。这似乎是因为iter(Foo)type上查找__iter__方法,而不是在Foo上(因为Footype对象)

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)

Tags: to实例infromforfootype情况
1条回答
网友
1楼 · 发布于 2024-04-25 06:10:52

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

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

相关问题 更多 >