python中的属性认识
class T(object): name ='windy' def bark(self): passt = 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':,#'__dict__': , '__get__': , '__weakref__': , '__doc__': None, 'name': 'windy'}复制代码