簡體   English   中英

如何判斷變量是全局變量還是局部變量?

[英]How can I tell whether a variable is global or local?

如何判斷Python中的變量是全局變量還是局部變量?

globals()將返回一個全局變量的字典

locals()將返回局部變量的字典

檢查變量的范圍:

if 'variable' in locals(): print("It's local") #Replace 'variable' with the variable
elif 'variable' in globals(): print("It's global") #But keep the quotation marks
else: print("It's not defined")

如果您不了解范圍,請訪問以下網址:https://stackoverflow.com/a/292502/7486769

如果您要做的只是列出一些文檔,那么您要做的就是創建一個在任何函數或類之外定義的變量的列表。

var1 = "something"

def foo():
    var2 = "something"

在上面, var1是全局的, var2是局部的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM