10

在 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"

能够在 Python 中为我正在处理的项目执行此操作会很方便(需要解析大量令人讨厌的 XML,将其转换为对象并能够调用方法会很好。

Python有等价物吗?

4

3 回答 3

18

在对象上定义一个__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
于 2010-09-03T18:01:39.440 回答
1

您可能想要__getattr__,尽管它适用于类属性和方法(因为方法只是作为函数的属性)。

于 2010-09-03T18:00:31.237 回答
0

我一直在寻找相同的方法,但由于方法调用是一个两步操作,例如: * 1. 获取属性 ( obj._getattr _ ) * 2. 调用它 ( obtainedObject._ call _ )

没有神奇的方法可以预测这两种行为。

于 2012-11-13T17:01:47.127 回答