gpt4 book ai didi

python - 如何在 Python 中获取类属性的定义顺序?

转载 作者:太空狗 更新时间:2023-10-29 22:17:04 26 4
gpt4 key购买 nike

我想定义代表数据结构的轻量级类。与许多数据结构一样,数据的顺序很重要。所以如果我继续定义这个:

class User(DataStructure):
username = StringValue()
password = StringValue()
age = IntegerValue()

我的意思是这是一个数据结构,首先是用户名字符串,然后是密码字符串,最后是整数形式的用户年龄。

如果你熟悉Python,你就会知道上面的类User是一个继承自type的对象。就像 Python 中的大多数其他对象一样,它将有一个 __dict__。这就是我的问题。此 __dict__ 是一个 HashMap ,因此 __dict__ 中类属性的顺序与它们的定义顺序没有任何关系。

有什么办法可以弄清楚实际的定义顺序吗?在我使用我能想到的一种不太理智的方法之前,我在这里问...

哦,说清楚一点,我想要的是一种从上面的定义中得到它的方法:['username', 'password', 'age']

最佳答案

Python 2.7 和 3.x 在集合模块中定义了一个 OrderedDict。我相信它使用链表来维护其项目的插入顺序。它将可迭代方法添加到标准可变映射方法。

您可以定义一个元类,它使用 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.

不幸的是,Python 2.7 语言引用中的等效部分 3.4.3 没有提到能够替换类 namespace 字典,也没有提到 __prepare__() 方法。所以这可能只有在 Python 版本 3 中才有可能。

关于python - 如何在 Python 中获取类属性的定义顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4220747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com