variable changes if I change a different variable

让人想犯罪 __ 提交于 2019-12-25 18:24:43

问题


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

why does a.value give me 11 when I didn't use a.add()?


回答1:


@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:

Method 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

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



回答2:


Because when you do b = a you're not creating a new object of the class number just passing the reference of the object which a references.



来源:https://stackoverflow.com/questions/45337788/variable-changes-if-i-change-a-different-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!