【发布时间】:2018-09-15 13:22:46
【问题描述】:
我正在编写一个程序,该程序涉及递归地创建一个可以作为参数传递的对象的实例。程序示例:
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) 似乎也可以工作。但我希望在课堂上而不是在程序的主体中完成复制。
【问题讨论】:
标签: python python-3.x class oop cloning