可能是重复问题:
Python中类似Ruby的method_missing技术的方法?
在Python中是否有类似于Ruby的method_missing技术用于拦截消息(方法调用)的技术?
可能是重复问题:
Python中类似Ruby的method_missing技术的方法?
在Python中是否有类似于Ruby的method_missing技术用于拦截消息(方法调用)的技术?
o.f(x)
时,它实际上是一个两步操作:首先,获取o
的f
属性,然后用参数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
__getattr__
方法并从中返回一个可调用对象。请注意,在属性查找期间,你无法决定所请求的属性是否打算被调用,因为Python会分两步完成此操作。