Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 be 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?

like image 656
Keith Palmer Jr. Avatar asked Sep 03 '10 17:09

Keith Palmer Jr.


1 Answers

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
like image 108
Juliano Avatar answered Oct 13 '22 01:10

Juliano