从一个局部函数中改变另一个变量

2024-04-26 13:08:48 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,下面是我的示例代码:

编辑:我应该在实际代码中指定\u 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()

我要做的是将这个_func()中的局部变量c更改为我在该函数中分配给它的值,以便它打印2而不是1。在

根据我在网上收集到的信息,这个函数c=2应该可以做到这一点,但它不起作用。我是做错了什么,还是我误解了?在

谢谢你的帮助。在


Tags: to函数代码from编辑示例returnthat
2条回答

将其包装在对象中并传递给that_func

def this_func():
    vars = {'c': 1}
    d = that_func(vars)
    print vars['c'], d

def that_func(vars):
    vars['c'] = 2
    return 1000

或者,可以将其作为常规变量传入,that_func可以返回多个值:

^{pr2}$

是的,你误解了。在

functions不是{}。你不能像那样访问function的变量。在

显然,这并不是可以编写的最聪明的代码,但是这段代码应该能告诉我们如何使用函数的变量。在

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()

相关问题 更多 >