在开始具体的代码验证之前,提出我的主观理解结论:
- 静态(static)的概念是限定类成员(属性变量,成员方法)的作用域,和C++的static声明有相同之处
- Python类中没有static的关键字。python实现上,没有self限定的变量和方法都是“静态的”,带self的就是普通的类成员。
- 所以python的静态与C++中的静态有较大区别,类和对象都能读取静态变量,而对象不能读取静态方法(参数错误,调用时多了一个self参数)。静态变量的赋值很奇怪!如果对象未对静态变量赋值,则类和对象分享相同变量地址(类赋值也会改变对象的值,同c++static机理);如果对象从新绑定静态变量,类中的值不受影响。
代码验证如下
>>> class test():
... value = 0
... def func():
... print("I am the class function")
...
>>> a = test()
>>> b = test()
>>> print(test.value,a.value,b.value)
0 0 0
>>> a.value = 1
>>> print(test.value,a.value,b.value)
0 1 0
>>> print(id(test.value),id(a.value),id(b.value))
10914400 10914368 10914400 # 注意, a的值地址单独变化
>>> test.value = 2
>>> print(test.value,a.value,b.value)
2 1 2
>>> print(id(test.value),id(a.value),id(b.value))
10914432 10914368 10914432 # 注意b和test的值地址是同时变化
>>> def func():
... print('I am the global function')
...
>>> test.func()
I am the class function
>>> a.func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes 0 positional arguments but 1 was given
>>> test.func = func
>>> test.func()
I am the global function
>>> a.func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes 0 positional arguments but 1 was given