How to get attributes in the order they are declared in a Python class?

笑着哭i 提交于 2019-12-23 10:03:27

问题


As described in PEP435, an enum can be defined this way:

class Color(Enum):
    red = 1
    green = 2
    blue = 3

And the resulting enum members of Color can be iterated in definition order: Color.red, Color.green, Color.blue.

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.

But in the definition of Color, we don't have something like a FormField, how can we implement this?


回答1:


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

This prints

OrderedDict([('__module__', '__main__'), ('red', 1), ('green', 2), ('blue', 3)])



回答2:


In Python 2.x you can use this horrible hack I wrote to answer a slightly different question, as a foundation for functionality of this sort. So, really, you can't. :-)



来源:https://stackoverflow.com/questions/16514286/how-to-get-attributes-in-the-order-they-are-declared-in-a-python-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!