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()
?
Because when you do
b = a
you're not creating a new object of the classnumber
just passing the reference of the object whicha
references.@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:
Method 2: