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?

Answer

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
  • 15
Reply Report
      • 2
    • Pretty good, although it might also be useful to define the nested function as function(*args) so that the body can use both the function name and any arguments passed. Depends on what Keith wants the methods to do. (Of course if there won't ever be any arguments to any of the methods, __getattr__ itself could return the result, thereby simulating fields instead of methods.)
      • 1
    • I do in fact want to be able to get the function arguments as well. Is the only neccessary change to define def function(): as def function(*args):? Or do I need to do something else too? (Python newbie, sorry!)
    • @Keith: If the function takes arbitrary arguments, then put *args in the argument list and it will receive a tuple with all the arguments. If it is a fixed number of arguments, then you can just go ahead and define function(a, b) directly, for example, to take two arguments.

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
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions