类变量和对象变量

  • 先上代码:
class Man():
    #直接定义的类的变量,属于类   
    #其中 gender, avg_height为基本数据类型,immutable
    #lis为列表类型,为mutable的
    gender = 'male'   
    avg_height = 1.75
    lis = ['hello', 'world']

    def __init__(self, name):
        self.name = name  #name在类的构造函数中定义,是属于对象的变量

a = Man('jason')
b = Man('tom')
 
#通过一个对象a访问一个变量x,变量的查找过程是这样的:
#先在对象自身的__dict__中查找是否有x,如果有则返回,否则进入对象a所属的类A的
#__dict__中进行查找
 
#对象a试图修改一个属于类的 immutable的变量,则python会在内存中为对象a
#新建一个gender变量,此时a就具有了属于自己的gender变量
a.gender = 'female'

#对象b直接调用给类变量进行Man.lis赋值等容易认为新建对象的方法,会直接给对象b新建这个对象
b.lis = ['olleh', 'world']
#若为append等建立在已有对象的基础上的方法则会去修改类变量
#b.lis.append('new')
#print ('a.lis',a.lis)
#print ('b.lis',b.lis) 
#print('class.lis:',Man.lis)

#可用对象的.__class__方法找到对象的类,然后修改类变量
a.__class__.lis = ['hello', 'dlrow']

Man.t = 'test' #此时Man的变量又多了t,但是对象a和b中没有变量t。
a.addr = '182.109.23.1' #给对象a定义一个变量,对象b和类Man中都不会出现

print ('a:dict',a.__dict__) #属于a的变量,有 name, gender, addr
print ('b:dict',b.__dict__)  #属于b的变量,只有name
print ('class man dict:',Man.__dict__) #属于类Man的变量,有 gender,avg_height,lis,但是不包括 name
#name是属于对象的变量 
 
print ('a.gender:',a.gender)  #female
print ('b.gender:',b.gender)  #male
 
print ('a.lis',a.lis) #['hello', 'dlrow']
print ('b.lis',b.lis) #['olleh', 'world']
print('class.lis:',Man.lis)#['hello', 'dlrow']

output:

a:dict {'name': 'jason', 'gender': 'female', 'addr': '182.109.23.1'}
b:dict {'name': 'tom', 'lis': ['olleh', 'world']}
class man dict: {'__module__': '__main__', 'gender': 'male', 'avg_height': 1.75, 'lis': ['hello', 'dlrow'], '__init__': <function Man.__init__ at 0x7f1f39f23bf8>, '__dict__': <attribute '__dict__' of 'Man' objects>, '__weakref__': <attribute '__weakref__' of 'Man' objects>, '__doc__': None, 't': 'test'}
a.gender: female
b.gender: male
a.lis ['hello', 'dlrow']
b.lis ['olleh', 'world']
class.lis: ['hello', 'dlrow']
未完待续...

猜你喜欢

转载自www.cnblogs.com/katachi/p/9986627.html