假设我有一个类似的函数:
def foo():
x = 'hello world'
如何让函数返回x
,这样我就可以将它用作另一个函数的输入或在程序体内使用该变量?我尝试使用return
然后使用x
另一个函数中的变量,但我得到了NameError
那样。
For the specific case of communicating information between methods in the same class, it is often best to store the information in self
. See Passing variables between methods in Python? https://stackoverflow.com/questions/9520075/ for details.
您可以使用return https://docs.python.org/3/reference/simple_stmts.html#return从函数返回值的语句,thisdoes not使返回的变量(值)在scope https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules来电者的。要在调用方中使用该值,您可以直接在语句中使用它或捕获变量中的值。
下面是一些代码来演示这一点:
def foo():
x = 'hello world'
return x # return 'hello world' would do, too
foo()
print(x) # NameError - x is not defined outside the function
y = foo()
print(y) # this works
x = foo()
print(x) # this also works, and it's a completely different x than that inside
# foo()
z = bar(x) # of course, now you can use x as you want
z = bar(foo()) # but you don't have to
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)