正如其他人提到的那样,在Python中,执行时o.f(x)
实际上是一个两步操作:首先,获取的f
属性o
,然后使用parameter对其进行调用x
。这是因为没有属性而失败的第一步f
,并且是调用Python magic方法的那一步__getattr__
。
因此,您必须实现__getattr__
,并且它返回的内容必须是可调用的。请记住,如果您也尝试获取o.some_data_that_doesnt_exist
,__getattr__
则将调用相同的名称,并且它不会知道它是“数据”属性还是要寻找的“方法”。
这是返回可调用对象的示例:
class MyRubylikeThing(object):
#...
def __getattr__(self, name):
def _missing(*args, **kwargs):
print "A missing method was called."
print "The object was %r, the method was %r. " % (self, name)
print "It was called with %r and %r as arguments" % (args, kwargs)
return _missing
r = MyRubylikeThing()
r.hello("there", "world", also="bye")
产生:
A missing method was called.
The object was <__main__.MyRubylikeThing object at 0x01FA5940>, the method was 'hello'.
It was called with ('there', 'world') and {'also': 'bye'} as arguments