您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Ruby在Python中的“ method_missing”

Ruby在Python中的“ method_missing”

正如其他人提到的那样,在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
python 2022/1/1 18:42:11 有293人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶