Bli*_*ixt 6 python oop hash class data-structures
我想定义应该代表数据结构的轻量级类.与许多数据结构的情况一样,数据的顺序很重要.所以,如果我继续定义:
class User(DataStructure):
username = StringValue()
password = StringValue()
age = IntegerValue()
Run Code Online (Sandbox Code Playgroud)
我暗示这是一个数据结构,其中首先是带有用户名的字符串,后跟带有密码的字符串,最后是用户的年龄作为整数.
如果你熟悉Python,你就会知道上面的类User是继承自的对象type.它就像Python中的大多数其他对象一样__dict__.这里存在我的问题.这__dict__是一个哈希映射,因此其中类属性__dict__的顺序与它们的定义顺序无关.
有什么方法可以找出实际的定义顺序吗?在我采用一种我能想到的不那么理智的方法之前,我在这里问...
哦,只是为了清楚,我想要的是一种方法来解决上述定义: ['username', 'password', 'age']
Python 2.7和3.x OrderedDict在collections模块中定义了一个.我相信它使用链表来维护其项目的插入顺序.它为标准的可变映射方法添加了可迭代的方法.
您可以定义一个元类,它使用一个OrderedDict而不是标准的无序dict作为__dict__数据结构类的命名空间.如果您为元类赋予特殊__prepare__()方法,则可以执行此操作.我没有试过这个,但根据文档,它是可能的:
从Python 3.1语言参考部分3.3.3数据模型 - 自定义类创建:
If the metaclass has a __prepare__() attribute (usually implemented as a class
or static method), it is called before the class body is evaluated with the
name of the class and a tuple of its bases for arguments. It should return an
object that supports the mapping interface that will be used to store the
namespace of the class. The default is a plain dictionary. This could be used,
for example, to keep track of the order that class attributes are declared in
by returning an ordered dictionary.
Run Code Online (Sandbox Code Playgroud)
不幸的是,Python 2.7语言参考中的等效部分3.4.3没有提到能够替换类命名空间字典而没有提及该__prepare__()方法.所以这可能只适用于Python版本3.
这是 Python 中根本没有得到很好支持的东西。Django 使用元类来处理它。请参阅这个问题:Django 如何知道渲染表单字段的顺序?
(总结:看看django.forms.forms.DeclarativeFieldsMetaclass,django.forms.forms.get_declared_fields以及creation_counter中如何使用django.forms.fields.Field。)