gpt4 book ai didi

python - 元类 - 不能替换类字典

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:30 24 4
gpt4 key购买 nike

运行这个(Python 3.3.1):

from collections import OrderedDict


class MyType(type):
@classmethod
def __prepare__(*args):
return OrderedDict()


class MyClass2(metaclass=MyType):

attr1 = 1
attr2 = 2
attr3 = 3
attr4 = 4
attr5 = 5

def __init__(self):
self.attr6 = 6

def func(self):
pass



print(MyClass2.__dict__.items())

我得到:

dict_items([('__weakref__', <attribute '__weakref__' of 'MyClass2' objects>), ('__dict__', <attribute '__dict__' of 'MyClass2' objects>), ('__init__', <function MyClass2.__init__ at 0x7f08a106dc20>), ('__doc__', None), ('attr4', 4), ('attr5', 5), ('attr2', 2), ('attr3', 3), ('attr1', 1), ('func', <function MyClass2.func at 0x7f089f995c20>), ('__module__', '__main__')])

类属性未按其定义顺序排序。

OrderedDict 用作类 __dict__ 我做错了什么?

最佳答案

mataclass 中的 __prepare__ 方法允许您提供自己的自定义对象来代替用于类初始化的 dict。但是,您不能更改该类实际使用的对象类型,它将是称为 mappingproxy 的内部类型的实例,并且是无序的。如果你想保留定义属性的顺序,你必须单独存储它:

class OrderedClass(type):
@classmethod
def __prepare__(metacls, name, bases):
return OrderedDict()

def __new__(cls, name, bases, classdict):
result = type.__new__(cls, name, bases, classdict)
result.member_names = list(classdict.keys())
return result


class MyClass2(metaclass=OrderedClass):

attr1 = 1
attr2 = 2
attr3 = 3
attr4 = 4
attr5 = 5

def __init__(self):
self.attr6 = 6

def func(self):
pass

>>> MyClass2.member_names
['__module__', '__qualname__', 'attr1', 'attr2', 'attr3', 'attr4', 'attr5', '__init__', 'func']

关于python - 元类 - 不能替换类字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16647307/

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