如何按在Python类中声明的顺序获取属性? [英] How to get attributes in the order they are declared in a Python class?
问题描述
如 PEP435 中所述,可以定义enum
方式:
As described in PEP435, an enum
can be defined this way:
class Color(Enum):
red = 1
green = 2
blue = 3
Color
的结果enum members
可以按照定义顺序进行迭代:Color.red, Color.green, Color.blue
.
And the resulting enum members
of Color
can be iterated in definition order: Color.red, Color.green, Color.blue
.
这让我想起了Django
中的Form
,其中可以按照在Form
子类中声明的顺序来渲染字段.他们通过维护字段计数器来实现此目的,每次实例化一个新字段时,计数器值都会增加.
This reminds me of Form
in Django
, in which fields can be rendered in the order they are declared in a Form
subclass. They implemented this by maintaining a field counter, every time a new field is instantiated the counter value get incremented.
但是在Color
的定义中,我们没有类似FormField
的东西,我们如何实现呢?
But in the definition of Color
, we don't have something like a FormField
, how can we implement this?
推荐答案
在Python 3中,您可以自定义使用元类声明类的名称空间.例如,您可以使用OrderedDict
:
In Python 3, you can customize the namespace that a class is declared in with the metaclass. For example, you can use an OrderedDict
:
from collections import OrderedDict
class EnumMeta(type):
def __new__(mcls, cls, bases, d):
print(d)
return type.__new__(mcls, cls, bases, d)
@classmethod
def __prepare__(mcls, cls, bases):
return OrderedDict()
class Color(metaclass=EnumMeta):
red = 1
green = 2
blue = 3
此打印
OrderedDict([('__module__', '__main__'), ('red', 1), ('green', 2), ('blue', 3)])
这篇关于如何按在Python类中声明的顺序获取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!