0

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()?

11
  • 6
    because a is b Commented Jul 26, 2017 at 21:32
  • 2
    You should read Facts and Myths about Python names and values. Commented Jul 26, 2017 at 21:33
  • Also see stackoverflow.com/questions/10151080/… Commented Jul 26, 2017 at 21:34
  • 1
    @juanpa.arrivillaga a = 1 ; b = a ; a += 1; print(a, b) ; # 2, 1 Commented Jul 26, 2017 at 21:40
  • 1
    @juanpa.arrivillaga Obviously this example re-assigns to a. The point is because ints are immutable b ia not affected. Commented Jul 26, 2017 at 21:40

2 Answers 2

0

@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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.