python – 如何读取类属性与声明的顺序相同?

我写一个元类读取类属性并将其存储在列表中,但我想列表(cls.columns)尊重声明顺序(即:mycol2,mycol3,zut,cool,menfin,a在我的例子) :

import inspect
import pprint

class Column(object):
    pass
class ListingMeta(type):
    def __new__(meta, classname, bases, classDict):
        cls = type.__new__(meta, classname, bases, classDict)
        cls.columns = inspect.getmembers(cls,lambda o:isinstance(o,Column)) 
        cls.nb_columns = len(cls.columns)
        return cls

class Listing(object):
    __metaclass__ = ListingMeta
    mycol2 = Column()
    mycol3 = Column()
    zut = Column()
    cool = Column()
    menfin = Column()
    a = Column()


pprint.pprint(Listing.columns)

结果:

[('a', <__main__.Column object at 0xb7449d2c>),
 ('cool', <__main__.Column object at 0xb7449aac>),
 ('menfin', <__main__.Column object at 0xb7449a8c>),
 ('mycol2', <__main__.Column object at 0xb73a3b4c>),
 ('mycol3', <__main__.Column object at 0xb744914c>),
 ('zut', <__main__.Column object at 0xb74490cc>)]

这不尊重Listing类的Column()属性的声明顺序。如果我直接使用classDict,它不会帮助:我怎么可以继续?

在Python 3中,只需使用OrderedDict并存储它的.keys(),然后传递整个dict来键入.__ new __(),像这样:

import collections 

class OrderedClassMembers(type):
    @classmethod
    def __prepare__(self, name, bases):
        return collections.OrderedDict()

    def __new__(self, name, bases, classdict):
        classdict['__ordered__'] = [key for key in classdict.keys()
                if key not in ('__module__', '__qualname__')]
        return type.__new__(self, name, bases, classdict)

class Something(metaclass=OrderedClassMembers):
    A_CONSTANT = 1

    def first(self):
        ...

    def second(self):
        ...

print(Something.__ordered__)
# ['A_CONSTANT', 'first', 'second']
http://stackoverflow.com/questions/4459531/how-to-read-class-attributes-in-the-same-order-as-declared

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 如何读取类属性与声明的顺序相同?