[英]How to call a function, it define in another function in python?
def out():
var1 = "abc"
print(var1)
def inner():
var2 = "def"
I want to call only "Inner" function... the final output should print only var2 not var1... 我只想调用“内部”函数...最终输出应该只打印var2而不是var1 ...
Thank you in advance 先感谢您
If you don't want to run some part of the function 'out' you could use parameters. 如果您不想运行“输出”功能的某些部分,则可以使用参数。
def out(choice=True):
if choice :
var1 = "abc"
print(var1)
else :
def inner():
var2 = "def"
print(var2)
inner()
You will not be able to call inner
from outside the out
function, since inner
is only defined inside out
, unless you create a reference to inner
from outside the out
function. 您将无法从
out
外部函数调用inner
,因为inner
仅在out
inner
定义,除非您从out
外部函数创建对inner
的引用。 In addition, inner
is not outputting anything since it does not have a print statement. 另外,由于
inner
没有打印语句,因此inner
不输出任何内容。
To combat this, you have two options: 为了解决这个问题,您有两种选择:
inner
in a broader scope (ie outside out
) and add to it a print(var1)
statement. inner
放在更广泛的范围内(即outside out
之外),并在其中添加一个print(var1)
语句。 inner
function be inside out
then just return inner
as a closure from out
, with the print statement also inside inner
; inner
的功能在里面out
然后就返回inner
为封闭的out
,用print语句也在里面inner
; or just call it from inside out
. out
调用它。 This has a side-effect of also executing whatever statements are inside out
up to returning the closure. out
了久违关闭。 The method your trying is called as nested functions: 您尝试的方法称为嵌套函数:
You can chek this answer for information about nested function in Python . 您可以查看该答案以获取有关Python中嵌套函数的信息。
Some other information about closure 有关关闭的其他信息
Another method is, 另一种方法是
def fun1():
x = 11
def fun2(a=a):
print x
fun2()
fun1()
Output: 输出:
prints 11
Example 2: 范例2:
def f1(x):
def add(y):
return x + y
return add
res = f1(5)
print(res(10)) # prints 15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.