python中的屬性認識

Whpitot發表於2018-04-04

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'}
複製程式碼

相關文章