Python 3从另一个函数中改变函数的变量

问题描述:

我想从testadder访问main中的测试变量,以便在testadder在main中被调用后它将添加1到测试中。Python 3从另一个函数中改变函数的变量

出于某种原因,我可以用这种方法将1添加到列表中,但不包含变量。非本地声明不起作用,因为函数不是依赖的。

有没有办法解决这个问题?

def testadder(test, testing): 
    test.append(1) 
    testing += 1 

def main(): 
    test = [] 
    testing = 1 
    testadder(test, testing) 
    print(test, testing) 

main() 
+0

你能详细说明'test'和'testing'应该是什么样子吗?理解你想做什么有点困难。 –

列表是可变的,但整数不是。返回修改的变量并重新分配它。

def testadder(test, testing): 
    test.append(1) 
    return testing + 1 

def main(): 
    test = [] 
    testing = 1 
    testing = testadder(test, testing) 
    print(test, testing) 

main() 
+0

还有一件事。假如我想要返回多个变量,那么它是否也可以工作?或者我需要以某种方式拆分它? – Uninvolved

+0

是的,'返回a,b'和'a,b = func()' –