如何深度复制具有动态添加属性的对象?
How to deepcopy a object with dynamically added attributes?
我偶然发现了这个问题,即 deepcopy 实际上并没有复制带有“即时”添加属性的整个对象。为什么会这样,有什么解决办法吗?
示例:
import pandas as pd
from copy import deepcopy
frame_one = pd.DataFrame({'hello': [1,2,3], 'world': [4,5,6]})
frame_one.name = 'foo'
frame_two = deepcopy(frame_one)
frame_two.name
错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "a_path\pandas\core\generic.py", line 5478, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'name'
这些属性不会被复制,因为 pandas 覆盖了 deepcopy。
您可以在第一个深度复制之后添加:
frame_two.__dict__ = deepcopy(frame_one.__dict__)
我偶然发现了这个问题,即 deepcopy 实际上并没有复制带有“即时”添加属性的整个对象。为什么会这样,有什么解决办法吗?
示例:
import pandas as pd
from copy import deepcopy
frame_one = pd.DataFrame({'hello': [1,2,3], 'world': [4,5,6]})
frame_one.name = 'foo'
frame_two = deepcopy(frame_one)
frame_two.name
错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "a_path\pandas\core\generic.py", line 5478, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'name'
这些属性不会被复制,因为 pandas 覆盖了 deepcopy。
您可以在第一个深度复制之后添加:
frame_two.__dict__ = deepcopy(frame_one.__dict__)