Suppose there is a class eg:
class Eg: ' ABCD ' def __init__ (self,name): = Name
Two instances A and B:
A = eg ('a'= eg ('b')
Then name is the instance variable, and n is the class variable. During the generation of an instance, class variables are stored in the memory location of the class, while instance variables are stored in the instance memory location.
At this point, the N value of two instances is printed, and the instance takes the value from the memory location of the class, so the values are ABCD:
Print (A.N, B.N)>>ABCD ABCD
When you modify the assignment of N in an instance of a, does the class's N value change? You can look at the following code:
classeg:n='ABCD' def __init__(self,name): Self.name=Namea= Eg ('a') b= Eg ('b')Print(A.N,B.N) A.N='EFGH' #只改变a实例中的nPrint(EG.N, A.N, B.N)>>ABCD ABCD>>ABCD efgh ABCD
You can see that only the value of A.N has changed, it can be judged that modifying the assignment of A.N will only equate to adding an n variable in the memory of a and assigning it as ' efgh ', that is, the A.N is only the EG.N of the map, and once the A.N is changed, the mapping relationship becomes its own assignment. In a B instance where there is no change, the memory value of the class is still taken, i.e.:
So, if you change the n value in a class, you can imagine what happens when you print A.N and B.N:
classeg:n='ABCD' def __init__(self,name): Self.name=Namea= Eg ('a') b= Eg ('b')Print(A.N,B.N) A.N='EFGH'Print(EG.N, A.N, B.N) EG.N='ABCDEFGH' #改变类中的nPrint(EG.N, A.N, B.N)>>ABCD ABCD>>ABCD efgh ABCD>>ABCDEFGH EFGH ABCDEFGH
The difference between a class variable and an instance variable is that the location of the memory is different, so the effect of this difference is obvious.
When there are many similar instances to be generated, if one attribute is a common attribute, then it is not necessary to instantiate in __init__ to consume memory, so one of the major functions of class variables is to save memory overhead. If there is an instance of this property other than the other instance, you only need to individually assign that parameter to the instance.
The difference and use of Python class variables and instance variables