Python中类变量和对象对象
1、打开python开发工具IDLE,新建‘clsvar.py’文件,写代码如下:
class Test:
rq = None
t1 = Test()
print (Test.rq)
print (t1.rq)
rq就是一个类变量

2、F5运行,打印出两None,也就是说类变量可以通过类和对象两种方式方式,推荐用类

3、用Test类添加一个对象变量,对象变量写在__init__中
class Test:
rq = None
def __init__(self,name):
self.name = name
t1 = Test('hello')
print (Test.__dict__)
print ('----')
print (t1.__dict__)

4、F5运行程序,先打印出Test类的变量rq和其他信息,再打印出对象变量

5、python还支持动态添加类变量,代码如下:
class Test:
rq = None
def __init__(self,name):
self.name = name
t1 = Test('hello')
Test.sj = '15:30'
print (Test.__dict__)
print ('----')
print (t1.__dict__)

6、python还支持动态添加对象变量,代码如下:
class Test:
rq = None
def __init__(self,name):
self.name = name
t1 = Test('hello')
t1.gender = 'female'
Test.sj = '15:30'
print (Test.__dict__)
print ('----')
print (t1.__dict__)

7、F5运行程序,通过打印信息发现动态添加的变量和建立类时的一样。
