The most terrifying thing is not making mistakes, but not finding them. Until now, I know that there is something wrong with my understanding of class variables.
Perhaps it may be because of the lack of frequent use of class variables, and this problem has not been discovered . I only learned what class variables are when I was watching C++ recently ?
I used to think that the only difference between class variables and member variables is that class variables can be accessed directly through class names and are static. Member variables need to be instantiated and accessed through instances.
I never expected that I ignored that there is only one class variable in one class, and each instance is the same. Modification in one instance will affect the class variable in other instances... (Although there is no bug caused by this usually, I still need to make up for cognitive vulnerabilities).
Here are 2 examples written in java and python :
public class OO{ public static String s; public String m; static{ s = "Ever"; } public static void main(String[] args){ OO o1 = new OO(); OO o2 = new OO(); o1.m = "Once"; //The value/address of class variables in different instances is the same System.out.println(o1.s); System.out.println(o2.s); System.out.println(o1.s.hashCode()); System.out.println(o2.s.hashCode()); o1.s = "123"; System.out.println(o2.s);//Change the class variable and affect other instances System.out.println(o1.m.hashCode()); System.out.println(o2.m.hashCode());//NullPointerException //Member variables have different addresses}} #!/bin/pythonclass B: def whoami(self): print("__class__:%s,self.__class__:%s"%(__class__,self.__class__))class C(B): count = 0 def __init__(self): super(C,self).__init__() self.num = 0 def add(self): __class__.count += 1 self.num += 1 def print(self): print("Count_Id:%s,Num_Id:%s"%(id(__class__.count),id(self.num))) print("Count:%d,Num:%d"%(__class__.count,self.num))i1 = C()i2 = C()i1.whoami()i2.whoami()#i1 member variable is increased by 1 time, i2 member variable is increased by 2 times, and class variable is increased by 3 times in total i1.add()i2.add()i2.add()i1.print()i2.print()The above is all about this article. The holiday will end tomorrow. I hope everyone will actively devote themselves to their work and continue to pay attention to the articles shared by the editor.