Python equivalent PHP __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" 

It would be convenient to have this in Python for the project I'm working on (a lot of nasty XML for parsing, it would be nice to turn it into objects and be able to just call methods.

Does Python have an equivalent?

+7
python php magic-methods
source share
3 answers

Define the __getattr__ method on your object and return a function (or 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 
+12
source share

You probably want __getattr__ , although it works with both class attributes and methods (because methods are just attributes that are functions).

+1
source share

I searched the same thing, but since the method call is a two-step operation: * 1. getting the attribute (obj. _Getattr _ ) * 2. call it (receivedObject. _Call _ )

There is no magic method that predicts both actions.

0
source share

All Articles