Python:为什么__getattr__捕获AttributeErrors? [英] Python: Why is __getattr__ catching AttributeErrors?

查看:201
本文介绍了Python:为什么__getattr__捕获AttributeErrors?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用 __ getattr __ 。我有一个复杂的递归代码库,重要的是让异常传播。

I'm struggling with __getattr__. I have a complex recursive codebase, where it is important to let exceptions propagate.

class A(object):
    @property
    def a(self):
        raise AttributeError('lala')

    def __getattr__(self, name):     
        print('attr: ', name)
        return 1      

print(A().a)

结果:

('attr: ', 'a')
1

为什么会这样的行为?为什么没有抛出异常?没有记录此行为( __ getattr __ 文档)。 getattr()只能使用 A .__ dict __ 。任何想法?

Why this behaviour? Why is no exception thrown? This behaviour is not documented (__getattr__ documentation). getattr() could just use A.__dict__. Any thoughts?

推荐答案

我只是将代码更改为

class A(object):
    @property
    def a(self):
        print "trying property..."
        raise AttributeError('lala')
    def __getattr__(self, name):     
        print('attr: ', name)
        return 1      

print(A().a)

,我们看到,确实首先尝试该属性。但是,由于它声称不在那里(通过提高 AttributeError ), __ getattr __()被称为最后手段

and, as we see, indeed the property is tried first. But as it claims not to be there (by raising AttributeError), __getattr__() is called as "last resort".

没有清楚的记录,但是可能会被计入在通常的地方没有找到属性查找时调用。

It is not documented clearly, but can maybe be counted under "Called when an attribute lookup has not found the attribute in the usual places".

这篇关于Python:为什么__getattr__捕获AttributeErrors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆