繁体   English   中英

Python __getattribute__和__setattr__

[英]Python __getattribute__ and __setattr__

我有以下代码:

#-*-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__ 这是我的想法: __init__self.x = x ,并且__setattr__捕获__init__self.__dict__[name] = value捕获__getattrbute__ 因此,将调用__getattribute__ 我的想法对吗? 怎么了 ?

箭头指向__setattr__调用__getattribute__

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM