【问题标题】:How to get attributes in the order they are declared in a Python class?如何按照在 Python 类中声明的顺序获取属性?
【发布时间】:2013-05-07 00:41:06
【问题描述】:

PEP435 中所述,enum 可以这样定义:

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

Color 的结果 enum members 可以按定义顺序迭代:Color.red, Color.green, Color.blue

这让我想起了Django 中的Form,其中的字段可以按照它们在Form 子类中声明的顺序呈现。他们通过维护一个字段计数器来实现这一点,每次实例化一个新字段时,计数器值都会增加。

但是在Color的定义中,我们没有FormField之类的东西,我们该如何实现呢?

【问题讨论】:

    标签: python metaclass


    【解决方案1】:

    在 Python 3 中,您可以使用元类自定义声明类的命名空间。例如,您可以使用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)])
    

    【讨论】:

    • 我想知道这是否可以在Python2.x中完成,以便我们做一个enum的backport。
    • 哦,我没看到你的答案,没错!
    • 没有。你在那里被简化为FormField-type hacks。
    【解决方案2】:

    在 Python 2.x 中,您可以使用 this horrible hack 我写的回答略有不同的问题,作为此类功能的基础。所以,真的,你不能。 :-)

    【讨论】:

      猜你喜欢
      • 2011-05-26
      • 2023-03-07
      • 2015-01-10
      • 2015-06-17
      • 2015-07-19
      • 2011-05-12
      • 2013-04-13
      • 2014-08-04
      相关资源
      最近更新 更多