1

Here is a code snippet:

 class h:
     v = 0
     def __init__(self):
             print(self.v)
     def add(self):
             self.v += 1
     def show(self):
             print(self.v)

 h.v
0
 a = h()
0
 a.add()
 a.show()
1
 h.v
0

In other words, when the instance of h updates the class variable, they no longer share it. Is this because the type of int is immutable? How can you share something like an int without the usage of a global?

Edit for clarity: h.v did not get updated with a.add(). I had expected it to.

11
  • 1
    You’d see the same thing if you did the same thing to a mutable value (reassigned an attribute containing it). Not sure what you’re asking re: sharing. Are you looking for type(self).v? Commented Sep 4, 2023 at 23:11
  • 3
    self.v += 1 is essentially self.v = self.v + 1. The self.v on the right hand side is read from the class, because it doesn't exist on the instance, but is then assigned to the instance self. If you want to modify a class attribute, you need to explicitly refer to the class object, not the instance. Commented Sep 4, 2023 at 23:14
  • 1
    BTW, that's not how your code snippet should behave!? add.show() should print 1, but h.v should print 0. Commented Sep 4, 2023 at 23:14
  • 1
    If you're mutating an object, sure, that works. But as you said, ints are immutable and can only be reassigned. Commented Sep 4, 2023 at 23:32
  • 1
    Note, self.v += 1 shadows the class variable with an instance variable, because you are assigning to the instance. This will always work that way regardless if the types involved (although, you may end up shadowing your class variable with an instance variable that is referring to the same object) Commented Sep 5, 2023 at 0:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.