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

Python 从另一个函数更改函数中的局部变量,python,function,variables,scope,Python,Function,Variables,Scope,首先,下面是我的示例代码: EDIT:我应该在实际代码中指定_func()已经返回另一个值,因此我希望它返回一个值,并另外更改c 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

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

EDIT:我应该在实际代码中指定_func()已经返回另一个值,因此我希望它返回一个值,并另外更改c

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()
编辑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更改为我在该_func()中指定的值,以便它打印2而不是1

从我在网上收集的信息来看,这个函数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()

将其包装在对象中,并将其传递给\u func

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

def that_func(vars):
    vars['c'] = 2
    return 1000
或者,您可以将其作为正则变量传入,并且_func可以返回多个值:

def this_func():
    c = 1
    c, d = that_func(c)
    print c, d

def that_func(c):
    c = 2
    return c, 1000

此函数是函数,而不是类
c
是该函数的一个局部变量-如果它是一个类,它将按照您的问题所建议的那样工作。但这需要对您的操作方式进行一些更改..对不起,我应该在我的实际代码中指定_func()已经返回了另一个值,所以我希望它返回一个值,并另外更改c。我已经编辑了这个问题。你可以返回多个值,以后再解包。可以吗?