【发布时间】:2017-06-27 20:40:59
【问题描述】:
我想复制一个在原始对象更改时不会更改的 python 类对象。这是我的简单工作示例:
class counterObject:
def __init__(self):
self.Value = 0
def incrementValue(self):
self.Value += 1
def printValue(self):
print(self.Value)
A = counterObject()
A.incrementValue()
A.printValue() #Prints 1
B = A
A.incrementValue()
B.printValue() #Currently prints 2. Want to be 1
据我了解,当我设置 B = A 时,这只是意味着 B 指向对象 A。因此,当我更改 A 时,它也会更改 B。是否可以改为使 B 成为具有与 A 所有相同属性的新实例,但在我更改 A 时不会更改?在我上面的例子中,当我增加 A 时,我希望 B 的值保持在 1。
如果 A 和 B 是列表而不是对象,我会写成 B = list(A)。我想我是在问类对象是否有类似的方法?
提前感谢您的帮助!
【问题讨论】:
-
听起来你想要一个单身......
-
Python 为您解答:来自 python 文档:docs.python.org/2/library/copy.html