Python中相当于PHP的__call()魔术方法是什么?
在PHP中,我可以这样做:
class MyClass
{
function __call($name, $args)
{
print('you tried to call a the method named: ' . $name);
}
}
$Obj = new MyClass();
$Obj->nonexistant_method(); // prints "you tried to call a method named: nonexistant_method"
这在我正在进行的一个项目中会很方便(有很多复杂的XML需要解析,把它们变成对象,然后可以直接调用方法会很好)。
Python有没有类似的功能呢?
3 个回答
0
我也在找这个,但因为调用方法是一个两步的操作,步骤是这样的:
- 第一步:获取属性(也就是用 obj._getattr_)
- 第二步:调用这个属性(用获得的对象来调用,也就是 obtainedObject._call_)
所以没有一种神奇的方法可以同时预测这两个动作。
2
你可能想用 __getattr__
,虽然它可以用在类的属性和方法上(因为方法其实就是一些函数的属性)。
20
在你的对象上定义一个 __getattr__ 方法,并从这个方法返回一个函数(或者一个闭包)。
In [1]: class A:
...: def __getattr__(self, name):
...: def function():
...: print("You tried to call a method named: %s" % name)
...: return function
...:
...:
In [2]: a = A()
In [3]: a.test()
You tried to call a method named: test