Ruby 的“method_missing”在Python中
Python 中是否有任何可用于拦截的技术消息(方法调用)就像 Ruby 中的 method_missing 技术一样?
Possible Duplicate:
Python equivalent of Ruby's 'method_missing'
Is there any technique available in Python for intercepting messages (method calls) like the method_missing technique in Ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如其他人提到的,在 Python 中,当您执行
of(x)
时,它实际上是一个两步操作:首先,获取o< 的
f
属性/code>,然后使用参数x
调用它。这是失败的第一步,因为没有属性f
,并且正是该步骤调用了 Python 魔术方法__getattr__
。所以你必须实现
__getattr__
,并且它返回的内容必须是可调用的。请记住,如果您还尝试获取o.some_data_that_doesnt_exist
,则会调用相同的__getattr__
,并且它不会知道它是“数据”属性还是“数据”属性。正在寻求的“方法”。这是返回可调用的示例:
产生:
As others have mentioned, in Python, when you execute
o.f(x)
, it's really a two-step operation: First, get thef
attribute ofo
, then call it with parameterx
. It's the first step that fails because there is no attributef
, and it's that step that invokes the Python magic method__getattr__
.So you have to implement
__getattr__
, and what it returns must be callable. Keep in mind, if you also try to geto.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:
produces:
您可以重载 __getattr__ 并从中返回一个可调用对象。请注意,您无法在属性查找期间决定是否要调用所请求的属性,因为 Python 分两步执行此操作。
You can overload
__getattr__
and return a callable from that. Note that you can NOT decide during attribute lookup whether the requested attribute is intended to be called, since Python does that in two steps.