2015-10-06 113 views
1

首先改变函数中的局部变量,这是我的示例代码:从另一个功能

编辑:我应该在我真正的代码已指定,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() 

我想要做的就是改变T中的局部变量c什么his_func()到我指定它在that_func(),所以它打印的价值2,而不是1

从我在网上收集的,this_func.c = 2要做到这一点,但它不起作用。我做错了什么,或者我误解了?

感谢您的帮助。

+0

' this_func'是一个函数,而不是一个类。 'c'是该函数的局部变量 - 如果它是一个类,它就会像你的问题所暗示的那样工作。但是,这需要一些改变,你如何做事情.. – whrrgarbl

回答

0

把它包在一个对象和把它传递给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可以返回多个值:

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

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

是的,你误解了。

functions不是class。你不能像这样访问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() 
+0

对不起,我应该指定,在我的真实代码中,that_func()已经返回另一个值,所以我想它返回一个值,并更改c此外。我编辑了这个问题。 – Matsern

+0

您可以随时返回多个值并稍后解压缩。可以吗? –