class Myclass: SOME_ARRAY = [] def __init__(self): self.SOME_ARRAY2 = [] #SOME_ARRAY has the same adress across all instances of the class. #SOME_ARRAY2 has a specific adress for each instance
Here is what the above code is Doing:
1. The class Myclass is defined.
2. The class variable SOME_ARRAY is defined.
3. The __init__ method is defined.
4. The __init__ method defines the instance variable SOME_ARRAY2.
Now, let’s create two instances of Myclass:
instance1 = Myclass()
instance2 = Myclass()
Let’s see what happens when we modify SOME_ARRAY:
Myclass.SOME_ARRAY.append(1)
print(Myclass.SOME_ARRAY)
# [1]
print(instance1.SOME_ARRAY)
# [1]
print(instance2.SOME_ARRAY)
# [1]
As you can see, modifying SOME_ARRAY modifies the value of SOME_ARRAY in all instances of Myclass.
Now, let’s see what happens when we modify SOME_ARRAY2:
instance1.SOME_ARRAY2.append(1)
print(instance1.SOME_ARRAY2)
# [1]
print(instance2.SOME_ARRAY2)
# []
As you can see, modifying SOME_ARRAY2 modifies the value of SOME_ARRAY2 in instance1, but not in instance2.
This is because SOME_ARRAY2 is an instance variable, and each instance of Myclass has its own instance variable SOME_ARRAY2.
Now, let’s see what happens when we modify SOME_ARRAY2 in the __init__ method:
class Myclass:
SOME_ARRAY = []
def __init__(self):
self.SOME_ARRAY2 = []
self.SOME_ARRAY2.append(1)
instance1 = Myclass()
instance2 = Myclass()
print(instance1.SOME_ARRAY2)
# [1]
print(instance2.SOME_ARRAY2)
# [1]
As you can see, modifying SOME_ARRAY2 in the __init__ method modifies the value of SOME_ARRAY2 in all instances of Myclass.
This is because the __init__ method is called when