Skip to main content
 首页 » 编程设计

python之将方法参数转发给另一个方法之self 需要从 locals() 中弹出

2025年05月04日14落叶无声

将被调用函数的数据委托(delegate)给另一个函数很简单:

def test2(a, b): 
    huh = locals() 
    print huh 
 
def test(a, b='hoho'): 
    test2(**locals()) 

但是,locals() 在调用方法时包含 self,这会妨碍尝试在一行中为方法调用做同样的事情:

class X(object): 
    def test2(self, a, b): 
        huh = locals() 
        print huh 
 
    def test(self, a, b='hoho'): 
        self.test2(**locals()) # no workie 
        test2(**locals()) # no workie either 

请您参考如下方法:

你根本不应该在这里使用 locals();使用 *args 和 **kw 来捕获参数并传递它们:

def test(self, *args, **kw): 
    self.test(*args, **kw)