在Python中克隆对象

时间:2018-09-15 13:22:46

标签: python python-3.x class oop cloning

我正在编写一个程序,该程序涉及递归地创建可能作为参数传递的对象的实例。程序示例:

from copy import copy
class test():
    def __init__(self, sample=None):
        if not sample:
            self.a = int(input())
            self.b = int(input())
        else:
            self = copy(sample)

# MAIN HERE..
sampleobj1 = test()
print (sampleobj1.a, sampleobj1.b)
sampleobj2 = test(sampleobj1)
print (sampleobj2.a, sampleobj2.b)

如何克隆对象(此处为sampleobj1),而不是手动将“ sample”的所有变量分配给self?我收到以下错误:

Traceback (most recent call last):
File "test.py", line 17, in <module>
print (sampleobj2.a, sampleobj2.b)
AttributeError: 'test' object has no attribute 'a'

为什么行self = sample无效?无论我做什么,我总是碰巧遇到相同的错误。单独复制属性似乎很好。但是我正在编写具有很多属性的代码,其中复制每个属性似乎有些冗长。

sampleobj3 = copy(sampleobj1)似乎也起作用。但是我希望在类中而不是在程序主体中完成复制。

1 个答案:

答案 0 :(得分:3)

self = sample行仅覆盖一个局部变量,而不替换最初存储在self中的对象。

要复制类的实例,您必须完全定义如何从现有对象构建新对象。

您可以通过定义__copy____deepcopy__方法来做到这一点。这些是copy.copycopy.deepcopy分别使用的dunder方法。

不过,请注意,在您的input中放入__init__是一种不好的做法,因为它阻碍了上述解决方案。您应该将逻辑和IO分开。

import copy

class test():
    def __init__(self, a, b):
        self.a, self.b = a, b

    def __copy__(self):
        return type(self)(self.a, self.b)

# Here we encapsulate the IO part of your code
 def test_factory():
    a = int(input())
    b = int(input())
    return test(a, b)

foo = test_factory()
... # input the attributes
bar = copy.copy(foo) # a copy of your object