Understand java and python class variables and their member variables

  • 2020-05-05 11:12:27
  • OfStack

The most terrible thing is not to make a mistake but not to find it. Until now, I didn't know I had a problem with class variables.
Probably because of the infrequent use of class variables, this problem has not been found. Recently, when I looked at C++, I realized what class variable is.
I used to think that the only difference between a class variable and a member variable was that the class variable could be accessed directly by the class name, which was static. Member variables need to be instantiated and accessed via the instance.
Never thought to ignore the class variables in a class only one, each instance is the same, in one instance will affect the change of class variables in other instances... (although bug is not usually the cause of this, it is still necessary to fill in the gaps in cognition).
Here are two examples written by 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";

    // Class variable values in different instances / The address 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);// Changing class variables affects other instances 

    System.out.println(o1.m.hashCode());
    System.out.println(o2.m.hashCode());//NullPointerException
    // Member variables have different addresses 
  }

}



#!/bin/python

class 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 The member variable of 1 time ,i2 The member variable of 2 time , Class variables have been added 3 time 
i1.add()
i2.add()
i2.add()
i1.print()
i2.print()

The above is all the content of this article, the holiday will be over tomorrow, I hope you are actively engaged in the work, continue to pay attention to this site for you to share the article.


Related articles: