[python3]: python --【class】类变量(类属性)
一、说明:
1、类变量:类变量,定义在【类内】且【函数外】。
1 class object:
2
3 # class_variable
4 icount = 0
5
6
7 def __init__(self):
8 # using class_variable
9 object.icount = object.icount + 1
10
11
12 def objnum(self):
13 print(f"object_number := { object.icount }")
2、类变量的使用方法【<类名> <.> <类变量名>】:class_name . class_variable
2.1、【object.icount】
2.1.1:class_name = object
2.1.2:class_variable = icount
二、代码
1 #!/usr/bin/env python3
2
3
4 class object:
5
6 # variable of class(class_variable)
7 # using variable of class: object.icount (class_name.class_variable)
8 icount = 0
9
10 def __init__(self, name):
11 self.icount = 1
12 self.__objname = name
13 object.icount = object.icount + 1
14 print(f"[constructor]# object_name:{ self.__objname }, object.icount = { object.icount } ")
15
16 def __del__(self):
17 object.icount = object.icount - 1
18 print(f"[destructor]# object_name:{ self.__objname }, object.icount = { object.icount } ")
19
20 def object_number(self):
21 print(f"\nobject_number := { object.icount }")
22 print(f"self_icount := { self.icount } \n")
23
24 def msg_name(self):
25 print(f"name := { self.__objname }")
26
27
28 if __name__ == '__main__':
29 x1 = object("f1")
30 x2 = object("f2")
31 x3 = object("f3")
32 x4 = object("f4")
33
34 x1.object_number()
35 x2.object_number()
36 x3.object_number()
37 x4.object_number()
三、运行结果
1 [constructor]# object_name:f1, object.icount = 1
2 [constructor]# object_name:f2, object.icount = 2
3 [constructor]# object_name:f3, object.icount = 3
4 [constructor]# object_name:f4, object.icount = 4
5
6 object_number := 4
7 self_icount := 1
8
9
10 object_number := 4
11 self_icount := 1
12
13
14 object_number := 4
15 self_icount := 1
16
17
18 object_number := 4
19 self_icount := 1
20
21 [destructor]# object_name:f1, object.icount = 3
22 [destructor]# object_name:f2, object.icount = 2
23 [destructor]# object_name:f3, object.icount = 1
24 [destructor]# object_name:f4, object.icount = 0
四、参考内容
1、 Python3 面向对象 -- https://www.runoob.com/python3/python3-class.html
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章的版权归属于【原创作者】; 转载或引用时请【保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/18010944