gpt4 book ai didi

python - 如何将 __iter__ 添加到动态类型?

转载 作者:行者123 更新时间:2023-11-28 22:06:44 25 4
gpt4 key购买 nike

来源

def flags(*opts):
keys = [t[0] for t in opts]
words = [t[1] for t in opts]
nums = [2**i for i in range(len(opts))]
attrs = dict(zip(keys,nums))
choices = iter(zip(nums,words))
return type('Flags', (), dict(attrs))

Abilities = flags(
('FLY', 'Can fly'),
('FIREBALL', 'Can shoot fireballs'),
('INVISIBLE', 'Can turn invisible'),
)

问题

如何将 __iter__ 方法添加到 Abilities 以便我可以遍历 choices

为什么?

这样我可以使用类似的东西

hero.abilities = Abilities.FLY | Abilities.FIREBALL

if hero.abilities & Abilities.FIREBALL:

for k, v in Abilities:
print k, v

在我的代码中无需使用任何魔数(Magic Number)或字符串,我还可以将标志集作为单个 int 保存到数据库,或以可读格式显示列表。

欢迎其他改进。

最佳答案

这里不需要使用动态类型;我将其重组为一个简单的类,例如:

class flags(object):
def __init__(self, *opts):
keys = [t[0] for t in opts]
words = [t[1] for t in opts]
nums = [2**i for i in range(len(opts))]
self.attrs = dict(zip(keys,nums))
self.choices = zip(nums,words)

def __getattr__(self, a):
return self.attrs[a]

def __iter__(self):
return iter(self.choices)

Abilities = flags(
('FLY', 'Can fly'),
('FIREBALL', 'Can shoot fireballs'),
('INVISIBLE', 'Can turn invisible'),
)

print Abilities.FLY
for k, v in Abilities:
print k, v

关于python - 如何将 __iter__ 添加到动态类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3217768/

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