Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python等价于PHPs\uuu call()魔术方法?_Php_Python_Magic Methods - Fatal编程技术网

Python等价于PHPs\uuu call()魔术方法?

Python等价于PHPs\uuu call()魔术方法?,php,python,magic-methods,Php,Python,Magic Methods,在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_me

在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是否有一个等价物?

您可能想要
\uuuu getattr\uuuu
,尽管它可以处理类属性和方法(因为方法只是函数的属性)。

在对象上定义一个方法,并从中返回一个函数(或闭包)


我也在寻找相同的方法,但由于方法调用是两步操作,如: *1.获取属性(obj.\u getattr\u) *2.调用它(获取对象。\u调用


没有神奇的方法可以预测这两个动作。

非常好,不过将嵌套函数定义为
function(*args)
可能也很有用,这样主体就可以同时使用函数名和传递的任何参数。这取决于Keith希望这些方法做什么。(当然,如果任何方法都不会有任何参数,
\uu getattr\uu
本身可以返回结果,从而模拟字段而不是方法。)事实上,我也希望能够获得函数参数。定义def function():as def function(*args)的唯一必要更改是:?或者我还需要做些别的事情吗?(Python新手,对不起!)@Keith:如果函数接受任意参数,那么将
*args
放入参数列表中,它将收到一个包含所有参数的元组。如果是固定数量的参数,那么您可以继续定义
函数(a,b)
例如,直接获取两个参数。
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