Skip to main content
 首页 » 编程设计

Python __getattribute__(或 __getattr__)模拟 php __call

2024年08月12日23qq78292959

我想创建一个有效地执行此操作的类(将一点 PHP 与 Python 混合)

  class Middle(object) : 
    #  self.apply is a function that applies a function to a list 
    #  e.g   self.apply = []  ... self.apply.append(foobar)        
    def __call(self, name, *args) : 
       self.apply(name, *args)    

因此允许代码说:

   m = Middle() 
   m.process_foo(a, b, c) 

在这种情况下,__call() 是 PHP __call() 方法,当在对象上找不到方法时调用该方法。

请您参考如下方法:

你需要定义__getattr__,它is called if an attribute is not otherwise found在你的对象上。

请注意,任何失败的查找都会调用 getattr,并且您不会像函数一样获取它,因此您必须返回将被调用的方法。

def __getattr__(self, attr): 
  def default_method(*args): 
    self.apply(attr, *args) 
  return default_method