理解java和python类变量以及类的成员变量
发布时间:2020-05-24 07:56:54 所属栏目: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";
//不同实例中的类变量值/地址相同
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);//更改类变量后影响了其他实例
System.out.println(o1.m.hashCode());
System.out.println(o2.m.hashCode());//NullPointerException
//成员变量具有不同的地址
}
}
#!/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的成员变量增加了1次,i2的成员变量增加了2次,类变量共增加了3次
i1.add()
i2.add()
i2.add()
i1.print()
i2.print()
以上就是本文的全部内容,明天假期就结束了,希望大家积极地投入到工作中,继续关注小编为大家分享的文章。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
