[英]Can I avoid to use the "value" attribute to actually retrieve the value of an element in an Enum?
Imagine a class that works like a container of database table information (table names and columns).想象一个 class 就像数据库表信息(表名和列)的容器一样工作。
This is an implementation.这是一个实现。
class Tables(Enum):
class Table1:
""" documentation for first table """
NAME = "My First Table"
COL11 = "col11"
COL12 = "col12"
COL13 = "col13"
class Table2:
""" documentation for second table """
NAME = "My Second table"
COL21 = "col21"
COL22 = "col22"
COL23 = "col23"
My goal would be to access the value of the enum (which are the classes Table1
or Table2
) without explicitly calling the value
attributes.我的目标是在不显式调用value
属性的情况下访问枚举的值(它们是类Table1
或Table2
)。
So if for example I want to concatenate the first two columns of the first table I want to write因此,例如,如果我想连接我想写的第一个表的前两列
TABLES.TABLE1.COL1 + TABLES.TABLE1.COL2
instead of代替
TABLES.TABLE1.value.COL1 + TABLES.TABLE1.value.COL2
I need the class Tables
to be an enum since I need to iterate over it and I need single tables to be classes because I want to add a small documentation on each of them.我需要将 class Tables
作为枚举,因为我需要对其进行迭代,并且我需要将单个表作为类,因为我想在每个表上添加一个小文档。
You can use a namedtuple
for the outer Tables
class and normal classes for the actual table definitions:您可以将命名元组用于外部Tables
namedtuple
和普通类用于实际表定义:
from collections import namedtuple
class Table: pass
class Table1(Table):
""" documentation for first table """
NAME = "My First Table"
COL11 = "col11"
COL12 = "col12"
COL13 = "col13"
class Table2(Table):
""" documentation for second table """
NAME = "My Second table"
COL21 = "col21"
COL22 = "col22"
COL23 = "col23"
Tables = namedtuple("Tables", (t.__name__ for t in Table.__subclasses__()))
TABLES = Tables(*Table.__subclasses__())
This allows writing TABLES.Table1.COL11
and also allows iterating over TABLES
.这允许编写TABLES.Table1.COL11
并允许迭代TABLES
。
Inheritance and __subclasses__
is only used to add the table classes automatically to the namedtuple. Inheritance 和__subclasses__
仅用于将表类自动添加到 namedtuple。
If all you need is your class to be iterable, you can use a use a metaclass.如果您只需要 class 是可迭代的,则可以使用元类。 Register your nested class to participate in the iteration by inheriting from .Value
注册您的嵌套 class 以通过继承.Value
参与迭代
class BagOfClass(type):
class Value:
pass
def __iter__(klass):
for attr_value in vars(klass).values():
if isinstance(attr_value, type) and issubclass(
attr_value, BagOfClass.Value
):
yield attr_value
class Tables(metaclass=BagOfClass):
class Table1(BagOfClass.Value):
"""documentation for first table"""
NAME: str = "My First Table"
COL11: str = "col11"
COL12: str = "col12"
COL13: str = "col13"
class Table2(BagOfClass.Value):
"""documentation for second table"""
NAME: str = "My Second table"
COL21: str = "col21"
COL22: str = "col22"
COL23: str = "col23"
print(*[table.NAME for table in Tables])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.