当前位置: 动力学知识库 > 问答 > 编程问答 >

python - __getattr__ equivalent for methods

问题描述:

When an attribute is not found object.__getattr__ is called. Is there an equivalent way to intercept undefined methods?

网友答案:

Methods are attributes too. __getattr__ works the same for them:

class A(object):

  def __getattr__(self, attr):
    print attr

Then try:

>>> 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
网友答案:

There is no difference. A method is also an attribute. (If you want the method to have an implicit "self" argument, though, you'll have to do some more work to "bind" the method).

网友答案:

you didn't return anything.

class A(object):

  def __getattr__(self, attr):
    return attr

should work

网友答案:

If one wants the attribute to behave like a method, provide a function! E.g. to make a.thing() works:

class A:

    def __init__(self, id):
        self.id = id

    def __getattr__(self, name):
        def inner():
            return self.id, name
        return inner

Then,

>>> a = A(42)
>>> a.thing
<function __main__.inner>
>>> a.thing()
(42, 'thing')
分享给朋友:
您可能感兴趣的文章:
随机阅读: