Skip to main content
 首页 » 编程设计

python:如何在不更改参数的情况下调用函数

2025年05月04日11TianFang

如果我有一个函数:

def foo(self, a, b): 
    c = a + b 
    return c 

如何在不更改函数中的 c 的情况下调用 foo?假设我在另一个函数中调用了 foo:

def bar(self): 
    z = self.foo(2, 4) 
    return (z) 

然后我想在一个单独的函数中再次调用 foo,但我想要从调用“bar”时开始的 c。

def baz(self): 
    self.foo(?, ?) # trying to just get c, without any changes. 

基本上,我试图在类里面保留一个帐户,以便其他类(class)可以访问同一帐户;只是一个简单的天平,加减钱。

谢谢。

请您参考如下方法:

将 c 存储为类变量或全局变量并覆盖函数以返回旧值。

例如

class SomeClass: 
     def foo(self, a=None, b=None): 
        if a and b: 
            c = a + b 
            self.stored_c = c 
            return c 
        return self.stored_c 

注意:您必须处理何时更新 stored_c 和任何并发问题。

更新:WRT glglgl 的评论,针对方法重载进行了更新。