2010-06-16 40 views
8

我有一個非常基本的問題。Python - 從函數輸出?

假設我調用一個函數,例如,

def foo(): 
    x = 'hello world' 

如何獲得的功能以這樣的方式,我可以用它作爲輸入其他功能或體內使用的變量返回X一個程序?

當我使用收益和其他功能我得到一個NameError中調用該變量。

+5

我真的推薦你在這裏閱讀python教程:http://docs.python.org/tutorial/index.html – 2010-06-16 12:09:53

回答

21
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 
+1

你忘記了一個「return x的例子,以便我可以使用它作爲輸入另一個功能」,這是最容易做這樣的酒吧(富())' – 2010-06-17 00:53:30

+0

@Evan鰈魚:好一點,謝謝。我編輯了我的答案。 – 2010-06-17 05:17:43

3
>>> def foo(): 
    return 'hello world' 

>>> x = foo() 
>>> x 
'hello world' 
2

您可以使用global語句,然後實現你想要什麼,而不從 函數返回值。例如,您可以執行以下操作:

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

foo() 
print x 

上述代碼將打印出「hello world」。

但是請警告說,「全球性」的使用是根本不是一個好主意,這是更好地避免了在我的例子顯示使用。

還要檢查大約在Python global語句使用此相關的討論。

+2

從技術上講,這是Seafoid的問題的解決方案,但pythonically,這是最壞的情況,方案(因爲你已經指出)。 – 2010-06-16 12:20:53