python - python 中的 __getattr__ 方法

标签 python oop delegates

我今天遇到这段代码,它看起来很困惑

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/

相关文章:

python - 从 Python 脚本查询远程 API

javascript - 我想要 JavaScript 中的子对象

c++ - 类构造函数不保存变量

c# - 如何将委托(delegate)分配为某些已实现接口(interface)的方法

Python 日期时间增量 - 15 分钟?

python - 需要有关解决 Wagtail/SQL Azure 兼容性问题的建议

delegates - Swift 使用用 Objective-C 编写的委托(delegate)

ios - 委托(delegate)是否仍然不安全未保留?

python - 如何使用flask-login从数据库中注销用户

php - OOP——我应该开发多少类?