Zec*_*eck 12 python metaprogramming method-missing
Python中是否有任何可用于拦截消息(方法调用)的技术,如Ruby中的method_missing技术?
Ned*_*der 41
正如其他人所提到的,在Python中,当你执行时o.f(x),它实际上是一个两步操作:首先,获取f属性o,然后用参数调用它x.这是失败的第一步,因为没有属性f,而且是调用Python魔术方法的那一步__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