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

标签 python-3.x

我想要这样的东西:

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/

相关文章:

python-3.x - 如何调整 st.image 显示的图像大小

python - Pygame 窗口卡住并停止响应,我该如何解决这个问题?

python - 使用 Python 和 xml.etree.ElementTree 解析 XML 时遇到一些挑战

django - 如何使用 Django 检查 firebase 数据库中的 child 是否存在?

python - 为什么在 Python 多处理中将启动方法从 'spawn' 更改为 'fork' 不允许我再运行我的工作?

python - 为什么在我的类里面使用 __slots__ 不会改变大小?

python - 如何修复Python中的 "re.error: unterminated character set at position"?

python - python 中的瓷砖游戏

python - 如何在 Python 中扩展/连接两个迭代器

python - HTTP 错误 404 : Not Found - Post request not working