最可怕的不是犯错而是一直都没发现错误,直到现在我才知道自己对类变量的理解有问题。
大概可能也许是因为不常用类变量的原因吧,一直没有发现这个问题。最近在看C++时才知道了类变量到底是什么?
以前我一直觉得类变量和成员变量的唯一区别是类变量可以通过类名直接访问,是静态的。而成员变量需要实例化一个类后通过实例来访问。
万万没想到忽视了类变量在一个类中只有一个,各个实例中的都是同一个的,在一个实例中修改会影响其他实例中的类变量...(虽然平常也没有因为这个而引起什么bug,但是还是要补上认知的漏洞)。
这里有用java和python写的2个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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
//成员变量具有不同的地址
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#!/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 ()
|
以上就是本文的全部内容,明天假期就结束了,希望大家积极地投入到工作中,继续关注小编为大家分享的文章。