栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Ruby在Python中的“ method_missing”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 _missingr = 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611922.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号