如果我更改另一个变量,变量会发生变化

时间:2017-07-26 21:31:31

标签: python class

每当我创建一个类的实例时,创建一个为第一个实例分配的变量,并在第一个变量的第二个变量上使用该类的属性。

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?

2 个答案:

答案 0 :(得分:0)

因为当您执行b = a时,您只是传递number引用的对象的引用,而不是创建类a的新对象。

答案 1 :(得分:0)

@ juanpa.arrivillaga对您的问题提供了很好的评论。我只想添加如何修复代码以执行您期望的操作:

方法1:

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:

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