Python – 从函数输出?

我有一个非常基本的问题。

假设我调用一个函数,例如,

def foo(): x = 'hello world' 

我如何获得函数返回x的方式,我可以使用它作为另一个函数的input或使用程序的正文内的variables?

当我使用返回并在另一个函数内调用该variables时,我得到一个NameError。

 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 
 >>> def foo(): return 'hello world' >>> x = foo() >>> x 'hello world' 

你可以使用global语句,然后实现你想要的而不从函数返回值。 例如,你可以做如下的事情:

 def foo(): global xx = "hello world" foo() print x 

上面的代码将打印“你好世界”。

但请注意,使用“全球”不是一个好主意,最好是避免使用我的例子中所示。

另请参阅关于在Python中使用全局语句的相关讨论。