在学习python的途中,学习到关于类的知识的时候遇到了一个问题。类的命名空间,类作用域内可以定义一些可供所有成员访问的变量,例如:
class example:
count = 0
def save(self):
self.count++
在上述代码中,count 可以供所有的example类的实例访问读取,那么有一个疑问,每个实例的count 数值是一样的吗?一个改变所有的都改变吗?
于是我进行了下面的实验
>>> class hello4():
count = 0
def open_(self):
print self.count
def save_(self):
self.count += 1
>>> j = hello4()
>>> j.save_()
>>> j.count
1
>>> hello4.count
0
>>> hello4.count += 3
>>> hello4.count
3
>>> j.count
1
>>> k =hello4()
>>> k.count
3
>>> hello4.count += 1
>>> hello4.count
4
>>> k.count
4>>> j.count
1
>>> l = hello4()
>>> l.count
4
>>> l.save_()
>>> l.count
5
>>> k.count
4
>>> hello4.count
4
>>> hello4.count += 1
>>> k.count
5
>>> l.count
5
>>> hello4.count += 1
>>> l.count
5
>>> hello4.count
6
>>> k.count
6
>>>
在上面的测试实验中我首先创建了 j 对象,并使用 j.save_() 方法改变了j.count 的值,之后我们直接改变 hello4.count 的值,我发现 hello4.count 的值发生了变化,而 j.count 的值未发生变化。于是我又创建了 k 对象,此时可以看到,k实例继承了 hello4 类的 count 的值,并且我这次直接先改变 hello4.count 的值 ,奇怪的事情发生了,这次 k.count
的值发生了变化,而 j.count 的值仍未发生变化。于是我想到可能是我对于实例,有没有使用具体方法的先后顺序问题。于是我又创建了 l 对象,这次我先使用 l.save_()的方法,发现此时 l 实例的count 值不再随着 hello4.count
于是我得出一个结论:类的实例在刚开始创建时,实例中的(类作用域内全局)变量只有在调用相关方法对此值进行改变后,才真正属于实例自身,否则仍然和类绑定
接下来我又进一步做了如下实验:
>>> m =hello4()
>>> m.count
8
>>> m.open_()
8
>>> hello4.count += 1
>>> hello4.count
9
>>> m.count
9
>>> m.save_()
>>> m.count
10
>>> hello4.count += 1
>>> hello4.count
10
>>> m.count += 1
>>> m.count
11
>>> hello4.count
10
>>> n = hello4()
>>> n.count = 8
>>> n.count
8
>>> hello4.count
10
>>> b =hello4()
>>> b.count
10
>>> b.count += 5
>>> b.count
15
>>> hello4.count
10
>>> hello4.count += 5
>>> hello4.count
15
>>> b.count
15
>>>
可以看到,m,n,b 三个实例的现象验证了我的结论,同时也对我的结论作了一定的否定或者说补充。
最终的结论应该是: 一个类拥有在其作用域内的全局变量,可供所有实例访问时,实例在创建时首先继承其类的该变量值,并随实例的该变量而该变(但反过来不成立,可看b实例的现象),而在第一次改变该实例的值后,摆脱对该类的继承,真正完全属于该实例。
(小白,还没学会怎么在这个编辑器里加亮代码块,有点难看,非常不好意思,sorry)