[英]Changing the local variable of a function from within another function that is defined in said function.. Python
[英]Changing a local variable in a function from another function
首先,這是我的示例代碼:
編輯:我應該在我的真實代碼中指定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應該可以做到這一點,但是它不起作用。 我是在做錯事還是誤解了?
感謝您提供的所有幫助。
是的,你誤會了。
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()
將其包裝在一個對象中,並將其傳遞給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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.