Python __getattribute__和__setattr__

时间:2014-01-20 02:28:54

标签: python

我有以下代码:

#-*-coding:utf-8-*-
class A(object):
    def __init__(self, x):
        self.x = x

    def __getattr__(self, name):      # `__getattr__` will be called undefined attribute
        print "get: ", name
        return self.__dict__.get(name)

    def __setattr__(self, name, value):
        print "set:", name, value
        self.__dict__[name] = value

    def __getattribute__(self, name): # `__getattribute__` will be called all attributes
        print "attribute:", name
        return object.__getattribute__(self, name)

if __name__ == "__main__":
    a = A(10)
    print '---------------'
    a.x
    print '---------------'
    a.y = 20
    print '---------------'
    a.z

结果是:

set: x 10
attribute: __dict__
---------------
attribute: x
---------------
set: y 20
attribute: __dict__
---------------
attribute: z
get:  z
attribute: __dict__    

当我拨打a=A(10)时,为什么会调用__getattribute__?这是我的想法:self.x = x中有__init____setattr__抓住__init__self.__dict__[name] = value抓住__getattrbute__。因此,__getattribute__被调用。我的想法是对的吗?怎么了?

1 个答案:

答案 0 :(得分:2)

箭头指向__setattr__调用__getattribute__的位置:

def __setattr__(self, name, value):
    print "set:", name, value
    self.__dict__[name] = value
#       ^ attribute access!

__getattribute__处理所有显式属性查找,包括__dict__。我相信这是你已经得出的结论;我不太明白你想说什么。