python中的属性认识

150 阅读1分钟

python中的属性认识

class T(object):
    name ='windy'
    
    def bark(self):
        pass

t = T()
print dir(t)
#['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', 
#'__getattribute__', '__hash__', '__init__', '__module__', '__new__',  
#'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',  
#'__str__', '__subclasshook__', '__weakref__', 'bark', 'name']  

属性分为两类,一是python自带的,例如__calss__,__hash__
另一个是自定义属性 bark,hello

实例调用未定义的属性

实例直接调用未定义的属性时,程序会抛出异常。

    class TestA(object):
        pass
    
    testA = TestA()
    print testA.name    #AttributeError: 'TestC' object has no attribute 'name'
    print testA.bark()  #AttributeError: 'TestC' object has no attribute 'name'

实例访问属性的顺序

t先到t.__dict__ 搜寻属性key,如果找不到,又会到T.__dict__中搜寻属性key,如果还找不到,就会到T父类的__dict__去搜寻,都没有搜寻到就是会抛出一个exception

class T(object):
    name ='windy'
    def bark(self):
        pass

    def __get__(self, instance, owner):
        return '__get__windy'
        
t = T()
print t.__dict__  #{}空字典
print T.__dict__ 
t.name = 'windy'
print t.__dict__  #{'name': 'windy'}
#{'__module__': '__main__', 'bark': <function bart at 0x0000000005D2D0B8>,
#'__dict__': <attribute '__dict__' of 'TestC' objects>, '__get__': <function
#__get__ at 0x0000000005D2D128>, '__weakref__': <attribute '__weakref__' of
#'TestC' objects>, '__doc__': None, 'name': 'windy'}