如何将self分配给自己的另一个实例

uda*_*day 2 python python-3.x

假设我有一个班级:

import copy
class TestClass:
    def __init__(self, value):
        if isinstance(value, TestClass):
            self = value.deepcopy()
        else:
            self.data = value

    def deepcopy(self):
        return copy.deepcopy(self)
Run Code Online (Sandbox Code Playgroud)

我想编写代码,以便如果一个类的实例由同一个类的另一个实例初始化,它将成为deepcopy第二个类的一个.

现在,如果我尝试

In []: x = TestClass(3)
In []: x.data
Out[]: 3
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试

 In []: y = TestClass(x)
 Out[]: y.data
 ...
 AttributeError: 'TestClass' object has no attribute 'data'
Run Code Online (Sandbox Code Playgroud)

为什么没有deepcopy在实例x传递给它时发生y

mgu*_*arr 7

一个办法:

import copy
class TestClass:
    def __init__(self, value):
        if isinstance(value, TestClass):
            self.__dict__ = copy.deepcopy(value.__dict__)
        else:
            self.data = value
Run Code Online (Sandbox Code Playgroud)

这使您的示例工作.您想要做一个'复制构造函数',在Python对象中有一个__dict__包含所有成员的属性,因此您只需从原始对象复制字典并将其分配给新对象即可__dict__.