开发者

Python equivalent of PHPs __call() magic method?

In PHP, I can do something like this:

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"

This would be handy to b开发者_如何学运维e able to do in Python for a project I'm working on (lots of nasty XML to parse, it'd be nice to turn it into objects and be able to just call methods.

Does Python have an equivalent?


Define a __getattr__ method on your object, and return a function (or a closure) from it.

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


You probably want __getattr__, although it works on class attributes as well as methods (because methods are just attributes that are functions).


I was looking for the same but since the method calling is a two-step operation like: * 1. obtaining the attribute (obj._getattr_) * 2. calling it (obtainedObject._call_)

There's no magic method that predicts both actions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜