代码之家  ›  专栏  ›  技术社区  ›  hoju

__方法的getattr_uuu等效

  •  5
  • hoju  · 技术社区  · 15 年前

    object.__getattr__ 被称为。有没有一种等效的方法来拦截未定义的方法?

    3 回复  |  直到 15 年前
        1
  •  8
  •   detly    15 年前

    方法也是属性。 __getattr__ 同样适用于他们:

    class A(object):
    
      def __getattr__(self, attr):
        print attr
    

    >>> a = A()
    >>> a.thing
    thing
    >>> a.thing()
    thing
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'NoneType' object is not callable
    
        2
  •  10
  •   Arafangion    15 年前

    没有区别。方法也是属性。(如果你想让方法有一个隐式的“self”参数,你就必须做更多的工作来“绑定”这个方法)。

        3
  •  0
  •   Anthon    13 年前

    你什么也没还。

    class A(object):
    
      def __getattr__(self, attr):
        return attr