=========test.py
class a(object):
name = "Jim"
def __setattr__(self,name,value):
self.__dict__[name] = value
def __getattr__(self,name):
return name
b = a()
print dir(b)
print b.__dict__
print b.name
print b.notexists
b.name = "change"
print dir(b)
print b.__dict__
print b.name
print b.notexists
===========運行結果========
%python test.py
['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'name']
{}
Jim
notexists
['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'name']
{'name': 'change'}
change
notexists
============================
可以看到剛開始的時候b的__dict__對象裏面是空的沒有東西,當我們使用b.name訪問的時候直接訪問到的之前定義好的name屬性:"Jim"
當我們使用b.name = "change"後就默認調用了內置方法__setattr__,此時我並沒有直接操作self.name屬性,而是直接在修改了self.__dict__['name'] = 'change'.之後當我再用b.name訪問的時候獲得的就是__dict__中的name屬性的值。
於是我們可以看到__getattr__方法首先是在__dict__中找屬性名,然後在實例的屬性中找 ,然後再調用__getattr__方法獲得值。
希望能幫到妳