class DotDict(dict):
"""Make attribute-style dict.
It allows dict.key to paly with the item.
"""
def __getattr__(self, key):
return self[key]
......
>>> a = DotDict({'name': 'Something'})
>>> a.name
'Something'
>>> b = copy.deepcopy(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/copy.py", line 172, in deepcopy
copier = getattr(x, "__deepcopy__", None)
File "<stdin>", line 3, in __getattr__
KeyError: '__deepcopy__'
但是我网上查找答案把__getattr__改成这样
def __getattr__(self, key):
if key in self:
return self[key]
raise AttributeError(key)
就不报错了,但是不知道为什么,求大神解释啊,答案链接 https://www.peterbe.com/plog/must__deepcopy__
"""Make attribute-style dict.
It allows dict.key to paly with the item.
"""
def __getattr__(self, key):
return self[key]
......
>>> a = DotDict({'name': 'Something'})
>>> a.name
'Something'
>>> b = copy.deepcopy(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/copy.py", line 172, in deepcopy
copier = getattr(x, "__deepcopy__", None)
File "<stdin>", line 3, in __getattr__
KeyError: '__deepcopy__'
但是我网上查找答案把__getattr__改成这样
def __getattr__(self, key):
if key in self:
return self[key]
raise AttributeError(key)
就不报错了,但是不知道为什么,求大神解释啊,答案链接 https://www.peterbe.com/plog/must__deepcopy__