gpt4 book ai didi

python - 在类上定义魔法方法

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:20 25 4
gpt4 key购买 nike

我想定义一个可以迭代的单个对象,而不必先创建类再创建实例。像这样:

class Thing(object):
stuff = ["foo", "bar", "baz"]

@classmethod
def __iter__(cls):
return iter(cls.stuff)

for thing in Thing:
print thing

但是这实际上不起作用。有什么办法吗?

最佳答案

Ashwini 在他的评论中正确建议如下。这适用于 Python 2。

class ThingType(type):
__stuff__ = ["foo", "bar", "baz"]

@classmethod
def __iter__(cls):
return iter(cls.__stuff__)

class Thing(object):
__metaclass__ = ThingType

for thing in Thing:
print thing

这在 Python 3 中有效:

class ThingType(type):
__stuff__ = ["foo", "bar", "baz"]

@classmethod
def __iter__(cls):
return iter(cls.__stuff__)

class Thing(object, metaclass=ThingType):
pass

for thing in Thing:
print(thing)

关于python - 在类上定义魔法方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29759273/

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