【问题标题】:Ruby’s “method_missing” in Python [duplicate]Ruby 在 Python 中的“method_missing”[重复]
【发布时间】:2011-10-20 17:06:39
【问题描述】:

可能重复:
Python equivalent of Ruby's 'method_missing'

Python 中是否有任何技术可用于拦截消息(方法调用),例如 Ruby 中的 method_missing 技术?

【问题讨论】:

  • 你能描述一下你正在寻找的确切机制吗?
  • 我正在尝试在 Python 中实现 Rails 动态查找器之类的东西。
  • @Zeck,我的意思是,你能解释一下你在寻找什么,对于非 Ruby 的人吗?

标签: python metaprogramming method-missing


【解决方案1】:

正如其他人所提到的,在Python中,当你执行o.f(x)时,实际上是一个两步操作:首先,获取of属性,然后用参数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

【讨论】:

  • 这只能覆盖缺失的方法。如果我想涵盖缺少的成员和方法怎么办? “def __getattr__(self, name)”,name属性只是一个字符串,不足以告诉我这个名字的属性是方法,还是成员。
【解决方案2】:

您可以重载__getattr__ 并从中返回一个可调用对象。请注意,您无法在属性查找期间决定是否要调用请求的属性,因为 Python 分两步完成。

【讨论】:

  • 谢谢你们。我找到了解决方案here。但我只是想知道如何获取传递参数?
猜你喜欢
  • 2011-10-05
  • 2012-03-27
  • 2016-03-11
  • 2013-11-15
  • 2010-09-22
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
相关资源
最近更新 更多