如何复制复杂对象以便可以向其中添加新成员?当我尝试使用 deepcopy 时,它失败并显示“ TypeError: cannot serialize...”
最初的问题是我想向现有对象添加一些成员变量但不能,因为这样做会导致“ AttributeError: Object is fixed”
因此,想法是在具有添加成员的新类中创建原始对象的完整副本。
orig_obj = SomeSqlObject.get_root() # contents unclear, complex
class orig_expanded():
def __init__(self, replicable_object):
self.__dict__ = copy.deepcopy(replicable_object.__dict__)
self.added_member1 = None
self.added_list = []
expanded_thing = orig_expanded(orig_obj)
Run Code Online (Sandbox Code Playgroud)
但我得到:
TypeError: cannot serialize '_io.TextIOWrapper' object
Run Code Online (Sandbox Code Playgroud)
评论的后续回答,“什么是 SomeSqlObject?” 也许我的名字是错误的......公司的实际名称被混淆了。它是一种返回一个对象的方法,该对象表示(某种)树的基部该树被定义
class SomeSqlObject(ParentRegisterSet):
"""
Implements the functionality of the Device "root" Register Set.
"""
def __init__(self, db, v1, dg, ui):
self.__db__ = db
self.__dg__ = dg
self.__ui__ = ui
SomeSqlObject.__init__(self, v1, None)
# note: …Run Code Online (Sandbox Code Playgroud)