gpt4 book ai didi

Python __getattribute__ 和 __setattr__

转载 作者:行者123 更新时间:2023-12-01 05:26:33 27 4
gpt4 key购买 nike

我有以下代码:

#-*-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__ catch __init__, self.__dict__[name] = value catch __getattrbute__。因此,调用了 __getattribute__ 。我的想法对吗?怎么了?

最佳答案

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

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

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

关于Python __getattribute__ 和 __setattr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21225341/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com