Kei*_*Jr. 9 php python magic-methods
在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"
Run Code Online (Sandbox Code Playgroud)
这对于我正在处理的项目能够用Python来做是很方便的(要解析许多讨厌的XML,将它转换为对象并且能够只调用方法会很好.
Python有相同的功能吗?
Jul*_*ano 14
在对象上定义__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
Run Code Online (Sandbox Code Playgroud)