我有以下类(class):
class NewName:
def __init__(self):
self.Name = None
self.DecomposedAlias = OrderedDict([("Prefix", None),
("Measurement", None),
("Direction", None),
("Item", None),
("Location", None),
("Descriptor", None),
("Frame", None),
("RTorigin", None)])
self.Meaning = ""
self.SIUnit = OrderedDict([("ScaleFactor", None),
("Offset", None),
("A", None),
("cd", None),
("K", None),
("kg", None),
("m", None),
("mol", None),
("rad", None),
("s", None)])
self.NormalDisplayUnit = OrderedDict([("ScaleFactor", None),
("Offset", None),
("A", None),
("cd", None),
("K", None),
("kg", None),
("m", None),
("mol", None),
("rad", None),
("s", None)])
self.OrientationConvention = ""
self.ContactPerson = ""
self.Note = ""
self.SubType = None
self.RefersTo = []
如果我实例化这个类的一个新对象,我可以获得这样一个字典:
mynewname = NewName()
mynewdict = mynewname.__dict__
如果我希望 mynewdict 的排序方式与 NewName 的属性在其 __init__ 中实例化的方式相同,该怎么办?
做一些研究我发现 this ,但在我的例子中,我只会获得 ['__init__']。有没有办法指向 __init__ 中的属性?
为了完整起见,我应该提到我使用的是 Python 3.4。
请您参考如下方法:
你不能这样做,因为 __init__ 属性在实例创建之后调用(通过 __new__())所以如果你甚至覆盖 __new__() 并使用 __prepare__ 方法 using a metaclass ,您可以获得未在 __init__ 方法中定义的其他方法和属性的有序序列(dict 等)。
同样基于 this mail :
It's just not possible to have something different than a dict as a type's
__dict__. It's a deliberate limitation and required optimization.
但这并不意味着您无法获得类的有序属性列表。由于每个属性都由 __setattr__ 方法设置,您可以通过覆盖 __setattr__ 方法简单地将您的属性保存在有序字典中:
from collections import OrderedDict
class NewName:
ordered_attrs = OrderedDict()
def __setattr__(self, name, val):
object.__setattr__(self, name, val)
# Use setattr(self, name, val) if you don't want to preserve the attributes in instances `__dict__`
NewName.ordered_attrs[name] = val
def __init__(self):
# your __init__ body
mynewname = NewName()
print(list(NewName.ordered_attrs))
输出:
['Name', 'DecomposedAlias', 'Meaning', 'SIUnit', 'NormalDisplayUnit', 'OrientationConvention', 'ContactPerson', 'Note', 'SubType', 'RefersTo']
# Output of mynewname.__dict__
{'Note': '', 'Meaning': '', 'RefersTo': [], 'SIUnit': OrderedDict([('ScaleFactor', None), ('Offset', None), ('A', None), ('cd', None), ('K', None), ('kg', None), ('m', None), ('mol', None), ('rad', None), ('s', None)]), 'DecomposedAlias': OrderedDict([('Prefix', None), ('Measurement', None), ('Direction', None), ('Item', None), ('Location', None), ('Descriptor', None), ('Frame', None), ('RTorigin', None)]), 'SubType': None, 'Name': None, 'ContactPerson': '', 'NormalDisplayUnit': OrderedDict([('ScaleFactor', None), ('Offset', None), ('A', None), ('cd', None), ('K', None), ('kg', None), ('m', None), ('mol', None), ('rad', None), ('s', None)]), 'OrientationConvention': ''}
还有关于属性的设置,基于documentation :
If
__setattr__()wants to assign to an instance attribute, it should call the base class method with the same name, for example,object.__setattr__(self, name, value).
