gpt4 book ai didi

python-3.x - Python中的一组常量

转载 作者:行者123 更新时间:2023-12-02 19:22:18 25 4
gpt4 key购买 nike

我想要这样的东西:

class Fruits:
APPLE = 'APPLE'
ORANGE = 'ORANGE'
MANGO = 'MANGO'

# I want to access members easily
print(Fruits.APPLE)

# I want to list all members
print(list(Fruits))

# I want to check if a string belongs to the set
print('POTATO' in Fruits)

我想要纯字符串常量,分组到一个类中:

  • 成员(member)检查
  • 列出所有值

Python 枚举似乎不适合,因为:

  • 枚举不是普通字符串,引入一种新类型
  • 枚举需要使用.value
  • 不能直接序列化,否则很笨拙。

这可以用 Python 实现吗?我想为此我可能需要一些神奇的方法或元类?

最佳答案

如果您想自己实现,可以使用 元类__iter__ 方法。

class Meta(type):
def __new__(cls, name, bases, dct):
# this just iterates through the class dict and removes
# all the dunder methods
cls.members = [v for k, v in dct.items() if not k.startswith('__') and not callable(v)]
return super().__new__(cls, name, bases, dct)

# giving your class an __iter__ method gives you membership checking
# and the ability to easily convert to another iterable
def __iter__(cls):
yield from cls.members

class Fruits(metaclass=Meta):
APPLE = 'APPLE'
ORANGE = 'ORANGE'
MANGO = 'MANGO'


print(Fruits.APPLE)
print('APPLE' in Fruits)
print(list(Fruits))

关于python-3.x - Python中的一组常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62881486/

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