I have a problem in understanding of the notion of static variables in Python classes. According to Static class variables in Python, whenever we define a variable outside a method and inside a python class, this variable is static. This means this variable can be accessed without any need to instantiate an object from a class and can be accessed by the class name directly. For example:
class my_class:
i=12
def __init__(self,j):
self.j=j
instance=my_class(10)
my_class.i:
>12
instance.i:
>12
instance.i=13
instance.i:
>13
my_class.i:
>12
You can see that we can access the static variable i
through both instance object and the class name. However, when we change the value of i
for instance object it does not affect the value of the class(my_class.i
is still 12).
On the other hand, things totally change if we are working with array static variables.
Considering the similar example:
class my_class:
i=[]
def __init__(self,j):
self.j=j
instance=my_class(10)
my_class.i:
>[]
instance.i:
>[]
instance.i.append(13)
instance.i:
>[13]
my_class.i:
>[13]
You can see that when I change the variable for the array of instance object it also affects the class value. What is going on here? I would appreciate if someone could help me better understand this issue as it is not that much obvious to me. By the way, I have a Java background.