Python相当于Ruby的

Python相当于Ruby的

本文介绍了Python相当于Ruby的'method_missing'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:43