魔法方法__getattr__

当我们访问一个不存在的属性的时候,会抛出异常,提示我们不存在这个属性。而这个异常就是__getattr__方法抛出的,其原因在于他是访问一个不存在的属性的最后落脚点,作为异常抛出的地方提示出错再适合不过了。

class A(object):
    def __init__(self, value):
        self.value = value
    def __getattr__(self, item):
        print "into __getattr__"
        return  "can not find"
a = A(10)
print a.value
# 10
print a.name
# into __getattr__

posted @ 2022-09-29 19:02  Sherwin_szw  阅读(21)  评论(0编辑  收藏  举报