如果更改其他变量,变量也会更改 [英] variable changes if I change a different variable
本文介绍了如果更改其他变量,变量也会更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当我创建一个类的实例时,创建一个为第一个实例分配的变量,并在我的第一个变量更改的第二个变量上使用该类的属性。
Whenever I create an instance of a class, create a variable that's assigned that first instance, and use an attribute of the class on the second variable my first variable changes.
class number:
def __init__(self, value):
self.value = value
def add(self):
self.value = self.value + 1
a = number(10)
b = a
b.add()
a.value
为什么当我不使用 a.add()
时a.value给我11 ?
why does a.value give me 11 when I didn't use a.add()
?
推荐答案
@ juanpa.arrivillaga为您的问题提供了很好的评论。我只想添加如何修复您的代码以执行您期望的操作:
@juanpa.arrivillaga provided good comments to your question. I just want to add how to fix your code to do what you expect it to do:
class number:
def __init__(self, value):
self.value = value
def add(self):
self.value = self.value + 1
a = number(10)
b = number(a.value) # create a new object with the same value as 'a'
b.add()
a.value
方法2:
Method 2:
import copy
class number:
def __init__(self, value):
self.value = value
def add(self):
self.value = self.value + 1
a = number(10)
b = copy.copy(a) # make a shallow copy of the object a
# b = copy.deepcopy(a) # <-- that is what most people think of a "real" copy
b.add()
a.value
这篇关于如果更改其他变量,变量也会更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文