[英]Is there a way to use variable from outer function in the inner function body, in Python?
The pattern of the code that I try to build is: 我尝试构建的代码模式是:
def OuterFunction():
theVariable = 0
def InnerFunction():
# use theVariable from OuterFunction somehow
# the solution is not to use InnerFunction(theVariable) due to the reasons given in the text
InnerFunction()
My hopes were there is some keyword (like global) or a way to tell the interpreter to use theVariable from the outer method's scope. 我希望有某种关键字(例如global)或一种方法来告诉解释器使用外部方法范围内的theVariable。
Why I need it this way: A Python script that we run before has to become module now (the collection of methods). 为什么这样需要它:我们之前运行的Python脚本现在必须变成模块(方法的集合)。
OuterFunction did not exist before and InnerFunction is just an example for a big number of very complex methods that bear an already existing logic. OuterFunction以前不存在,而InnerFunction只是大量具有已经存在的逻辑的非常复杂方法的示例。
theVariable is just an example for multiple global variables that were used in the script in all of methods that InnerFunction represents. theVariable只是InnerFunction表示的所有方法中脚本中使用的多个全局变量的示例。
I do not want to change signatures of all methods, that are, by the way, nested. 我不想更改所有方法的签名,顺便说一下,它们都是嵌套的。
EDIT: 编辑:
Here is the code that crashes for me in every interpreter, with "local variable 'theVariable' referenced before assignment" error (so I could not just reference the variable): 这是在每个解释器中崩溃的代码,带有“分配前引用了本地变量'theVariable'”错误(因此我不能只引用该变量):
def OuterFunction():
theVariable = 5
def InnerFunction():
theVariable = theVariable + 1
print(theVariable)
InnerFunction()
OuterFunction()
EDIT2: EDIT2:
Seems trying to change the variable leads to the exception, which gives a wrong description. 似乎试图更改变量会导致异常,从而给出错误的描述。 If InnerFunction() is changed to contain only print(theVariable) statement it works. 如果将InnerFunction()更改为仅包含print(theVariable)语句,则它将起作用。
You could simply reference the 'theVariable' inside the nested InnerFunction, if you don't want to pass it's value as a parameter: 如果您不想将其值作为参数传递,则可以简单地在嵌套的InnerFunction内部引用“ theVariable”:
def OuterFunction():
# Declare the variable
theVariable = 42
def InnerFunction():
# Just reference the 'theVariable', using it, manipulating it, etc...
print(theVariable)
# Call the InnerFunction inside the OuterFunction
InnerFunction()
# Call the OuterFunction on Main
OuterFunction()
# It will print '42' as result
You can just reference the variable directly, as follows; 您可以直接直接引用变量,如下所示;
def outer():
x = 1
def inner():
print(x + 2)
inner()
outer()
Prints: 3
版画: 3
Would this be okay with you: 您可以这样吗:
def OuterFunction():
theVariable = 0
def InnerFunction(value):
return value + 1
theVariable = InnerFunction(theVariable)
return theVariable
This way you don't have to mess with scopes and your functions are pure . 这样,您就不必弄乱范围,并且您的函数是纯净的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.