我今天遇到这段代码,它看起来很困惑
class ClassOne:
def __init__(self,some_object):
self.not_important_attribute=some_object
class ClassTwo:
def __init__(self,some_object):
self.tmp=ClassOne(some_object)
def __getattr__(self,attr):
return getattr(self.tmp,attr)
a=ClassTwo('not_important_string')
print(getattr(a,'undefined_attribute',3))
当我们在最后一行使用 getattr
时,我们触发 SubClass
中的 __getattr__
方法,然后委托(delegate)给 getattr( self.tmp,attr)
函数,如果属性未定义且未提供默认值,该函数将引发异常。但是最后一行的值3怎么还是走完了所有的流程,最终返回到getattr(a,'undefined_attribute',3)
函数?。因为在委托(delegate) getattr(self.tmp,attr)
时我们没有默认值的槽,这怎么可能?
最佳答案
在你的情况下
getattr(self.tmp,attr)
引发 AttributeError 并且如果 getattr 有第三个参数(默认值)则它返回默认值而不是引发 AttributeError
关于python - python 中的 __getattr__ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57139500/