【问题标题】:What is __getattr__ order in the attribute lookup chain?属性查找链中的 __getattr__ 顺序是什么?
【发布时间】:2014-02-23 21:42:33
【问题描述】:

所以为了摆脱一些样板,我选择实现__getattr__ 来委派一些方法调用。问题是我在属性查找链中也有一个描述符,它们没有像我预期的那样交互。代码如下:

class C(object):
    attr = Descriptor()

    def __getattr__(self, item):
        # just returns a method for all items that match
        # a certain pattern

这就是问题所在。所有 Python 文档都提到 __getattr__ 仅在通常的查找链失败后被调用,但在这种情况下,__getattr__ 总是在 attr 之前被调用。

那么让描述符和__getattr__ 相互配合的正确方法是什么?

这是我观察到的:

a = C()
a.attr # goes to __getattr__ instead of C.attr.__get__

问题已解决。事实证明,如果描述符抛出异常,则查找会跳转到__getattr__

【问题讨论】:

  • 抛出哪个错误?我想知道。
  • 任何属性查找错误。如果您已经在描述符的 __get__ 方法内,并且该方法内的任何内容都引发了属性查找异常,则查找将继续使用 __getattr__

标签: python-2.7 attributes descriptor getattr name-lookup


【解决方案1】:

但在这种情况下,__getattr__ 总是在 attr 之前被调用

对不起,我不明白。

>>> class C(object):
    attr = property(fget = lambda self: 5)

    def __getattr__(self, item):
        # just returns a method for all items that match
        # a certain pattern

    return item

>>> C().x
'x'
>>> C().attr # attr.__get__ is called, not __getattr__
5

你能具体说明一下“和对方好好相处”是什么意思吗? 一种我理解的很好玩的方法:Method delegation in python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2015-02-16
    相关资源
    最近更新 更多