首先,这是我的示例代码:
编辑:我应该在我的实际代码中指定 that_func() 已经返回另一个值,所以我希望它返回一个值,并另外更改 c
编辑2:编辑代码以显示我的意思
def this_func():
c=1 # I want to change this c
d=that_func()
print(c, d)
def that_func():
this_func.c=2 #Into this c, from this function
return(1000) #that_func should also return a value
this_func()
我想要做的是将 this_func() 中的局部变量 c 更改为我在 that_func() 中分配给它的值,以便它打印 2 而不是 1。
根据我在网上收集的信息,this_func.c=2 应该可以做到这一点,但它不起作用。是我做错了什么,还是我理解错了?
感谢您的所有帮助。
最佳答案
是的,你误会了。
函数
不是类
。您无法像这样访问函数
的变量。
显然,这不是可以编写的最智能的代码,但是这段代码应该给出如何使用函数变量的想法。
def this_func():
c=1 # I want to change this c
c=that_func(c) # pass c as parameter and receive return value in c later
print(c)
def that_func(b): # receiving value of c from this_func()
b=2 # manipulating the value
return b #returning back to this_func()
this_func()
关于python - 从另一个函数更改函数中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32978440/