python - 从另一个函数更改函数中的局部变量

标签 python function variables scope

首先,这是我的示例代码:

编辑:我应该在我的实际代码中指定 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/

相关文章:

python - 是不是约定俗成的说函数被调用,方法被调用?

PHP 静态变量来存储函数数组

javascript - 将类似的点击事件操作转换为函数?

delphi - 为什么Assigned 对于未初始化的变量返回 true?

python - 每个 HIT 创建的作业不能超过 10 个

python - 在导入 pandas 之前我需要导入 NumPy 还是可以单独使用 pandas ?

python - list[-1 :][0] and list[len(list)-1]? 之间有什么区别

python - Django REST框架: raise error when extra fields are present on POST

c - C语言中变量的类型

C++ 变量声明