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.
type(self).v?self.v += 1is essentiallyself.v = self.v + 1. Theself.von the right hand side is read from the class, because it doesn't exist on the instance, but is then assigned to the instanceself. If you want to modify a class attribute, you need to explicitly refer to the class object, not the instance.add.show()should print1, buth.vshould print0.self.v += 1shadows 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)