问题描述
Python与Ruby的method_missing
方法等效吗?我尝试使用__getattr__
,但是此钩子也适用于字段.我只想拦截方法调用. Python的实现方式是什么?
What is Python's equivalent of Ruby's method_missing
method? I tried using __getattr__
but this hook applies to fields too. I only want to intercept the method invocations. What is the Python way to do it?
推荐答案
Python中属性和方法之间没有区别.方法只是一个属性,其类型仅为instancemethod
,碰巧可以调用(支持__call__
).
There is no difference in Python between properties and methods. A method is just a property, whose type is just instancemethod
, that happens to be callable (supports __call__
).
如果要实现此目的,您的__getattr__
方法应返回一个函数(一个lambda
或一个常规的def
,无论您需要什么套件),并可能在调用后进行检查.
If you want to implement this, your __getattr__
method should return a function (a lambda
or a regular def
, whatever suite your needs) and maybe check something after the call.
这篇关于Python相当于Ruby的'method_missing'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!