[英]Correctly calling variables inside a function
舉個例子
def Test():
Function = 'one'
print(Function)
如何做到這一點? 此刻我得到
NameError:名稱“功能”未定義
你不能那樣做。 Function
僅在Test()
方法內部定義。
如果需要,應使該方法返回字符串,如下所示:
def Test():
Function = 'one'
return Function
a = Test()
print(a)
該變量不在該函數的范圍內。 要么調用該函數,要么在最壞的情況下也可以使用global
關鍵字。
方式1(更好的選擇):
def Test():
Function = 'one'
return Function
#If you print Function now, you will get the name error!
print(Function)
>>> NameError: name 'Function' is not defined
# If you call the function that works!!
print (Test())
>>> one
方式2(最糟糕的一種):
>>> Function=''
>>> def Test():
global Function
Function = 'one'
>>> print(Test())
None
>>> print(Function)
one
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.