gpt4 book ai didi

python - `__dict__`什么时候重新初始化?

转载 作者:行者123 更新时间:2023-12-01 00:56:14 24 4
gpt4 key购买 nike

我对 dict 进行子类化,以便属性与键相同:

class DictWithAttr(dict):
def __init__(self, *args, **kwargs):
self.__dict__ = self
super(DictWithAttr, self).__init__(*args, **kwargs)
print(id(self), id(self.__dict__))

def copy(self):
return DictWithAttr(self.__dict__)

def __repr__(self):
return repr({k:v for k, v in self.items() if k != '__dict__'})

它按预期工作:

d = DictWithAttr(x=1, y=2)    # 139917201238328 139917201238328
d.y = 3
d.z = 4
d['w'] = 5
print(d) # {'x': 1, 'y': 3, 'z': 4, 'w': 5}
print(d.__dict__) # {'x': 1, 'y': 3, 'z': 4, 'w': 5}
print(d.z, d.w) # 4 5

但是如果我将 __setattr__ 重写为

    ...
def __setattr__(self, key, value):
self[key] = value
...

然后 __dict__ 将在初始化时重新创建,并且属性将变得不可访问:

d = DictWithAttr(x=1, y=2)    # 140107290540344 140107290536264
d.y = 3
d.z = 4
d['w'] = 5
print(d) # {'x': 1, 'y': 3, 'z': 4, 'w': 5}
print(d.__dict__) # {}
print(d.z, d.w) # AttributeError: 'DictWithAttr' object has no attribute 'z'

添加如下配对的 __getattr__ 将绕过 AttributeError

    ...
def __getattr__(self, key):
return self[key]
...

__dict__仍然被清除:

d = DictWithAttr(x=1, y=2)    # 139776897374520 139776897370944
d.y = 3
d.z = 4
d['w'] = 5
print(d) # {'x': 1, 'y': 3, 'z': 4, 'w': 5}
print(d.__dict__) # {}
print(d.z, d.w) # 4 5

感谢您的任何解释。

最佳答案

没有重新初始化。您的问题是 self.__dict__ = self 命中您的 __setattr__ 覆盖。它实际上并没有改变用于属性查找的字典。它正在为 self 上的 '__dict__' 键设置一个条目,并保持属性字典不变。

如果您想保留(毫无意义的)__setattr__ 覆盖,您可以在 __init__ 中绕过它:

object.__setattr__(self, '__dict__', self)

但删除 __setattr__ 覆盖会更容易。当您这样做时,也取出 __repr__ - 一旦您修复了代码,出现 '__dict__' 键的唯一原因是用户设置他们自己这样做,如果他们这样做,你应该展示出来。

关于python - `__dict__`什么时候重新初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233721/

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