前言:
虽然python支持在 实例方法中 更改 类成员变量, 但是最好不要这样做。
与java c++的不同:
设置实例属性可以在实例创建后的任意时间进行,也可以在能够访问实例的代码中进行。构造器__init()__
是设置这些属性的关键点之一。
在C++ Java中所有属性使用前必须要声明。 (没想到Python的操作竟然如此的骚, 当然骚是有代价的, 需要你更慎重的在运行时创建类的属性)
用法总结:
1. 类成员变量在方法之外,就是类成员变量。实例的成员变量在self中声明。
2. 类成员方法不需要, 也不能传任何参数。 也可以添加一个@staticmethod
3. 实例的成员方法,必须要传一个self参数。 有没有参数其实就可以区分它是静态方法, 还是实例方法。
class A:
## this a class static variable.
static_val = "static_val"
def __init__(self):
self.instance_val = "instance_val"
## in python3, you can not give it a param cls as you do in python2.x
@staticmethod
#if you @staticmethod, the compiler will deal the method as a static method.
def static_test():
## if you code in this way. it doesn't work.
## because you create a local variables named "static_val"
## when you exit the "test" function.
## the variable "static_val" is gone
## static_val = "static_val_test"
A.static_val = "static_val_test"
'''
if the method uses a static variable,
then the method would be a static method.
the following code is wrong.
print("change the instance_val in the static method.")
instance_val = "instance_val_test"
'''
'''
you must give a param "self"(you can give it another name).
or you get
TypeError: instance_test() takes 0 positional arguments
but 1 was given
'''
##@static_method
'''if you code it @staticmethod before a instance method.
the compiler will pass no param to the method.
it will return an error'''
def instance_test(self1):
#you can
self1.instance_val = "instance_val_test"
##this isn't a good way to change static value in a instance method.
A.static_val = "static_val_test_in_instance_val"
## you can access it. it's ok.
print(f"[instance_test] --> static_val is {A.static_val}")
##can not get class attr by className. eg. A.instance_val
a = A()
print(a.instance_val)
print(A.static_val)
print(a.static_val)
A.static_test()
print(A.static_val)
a.instance_test()
print(a.instance_val)
A.run_time_add_var = "run_time_add_var"
print(A.run_time_add_var)
a.run_time_instance_add_ver = "run_time_instance_add_ver"
print(a.run_time_instance_add_ver)
输出结果:
PS E:\python_projects> python .\class_static.py
instance_val
static_val
static_val
static_val_test
[instance_test] --> static_val is static_val_test_in_instance_val
instance_val_test
run_time_add_var
run_time_instance_add_ver