问题描述
Python中是否有诸如Ruby中的method_missing技术之类的用于拦截消息(方法调用)的技术?
Is there any technique available in Python for intercepting messages (method calls) like the method_missing technique in Ruby?
推荐答案
正如其他人所提到的,在Python中,当您执行o.f(x)
时,它实际上是一个两步操作:首先,获取f
属性o
,然后使用参数x
调用它.因为没有属性f
,所以第一步失败了,而这是调用Python魔术方法__getattr__
的那一步.
As others have mentioned, in Python, when you execute o.f(x)
, it's really a two-step operation: First, get the f
attribute of o
, then call it with parameter x
. It's the first step that fails because there is no attribute f
, and it's that step that invokes the Python magic method __getattr__
.
因此您必须实现__getattr__
,并且它返回的内容必须是可调用的.请记住,如果您还尝试获取o.some_data_that_doesnt_exist
,则将调用相同的__getattr__
,并且它不会知道它是数据"属性还是正在寻找的方法".
So you have to implement __getattr__
, and what it returns must be callable. Keep in mind, if you also try to get o.some_data_that_doesnt_exist
, the same __getattr__
will be called, and it won't know that it's a "data" attribute vs. a "method" that being sought.
以下是返回可调用对象的示例:
Here's an example of returning a callable:
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
这篇关于Ruby在Python中的"method_missing"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!