(2023.03.20 Mon)
Python變量有四種作用域(scope),按覆蓋范圍從小到大依次是
- local
- enclosing
- global
- built-in
Local scope
創(chuàng)建于函數(shù)中的變量,只在函數(shù)范圍內(nèi)有效,而函數(shù)外使用時將無效篮迎。該變量屬于函數(shù)的局部作用域(local scope)疯搅。
Enclosing scope
enclosing作用域發(fā)生在有嵌入式函數(shù)的場合蔫耽。嵌入式函數(shù)至少有一個內(nèi)部函數(shù)和外部函數(shù)(outside function)解幼。當(dāng)一個變量在外部函數(shù)中定義,則該變量在函數(shù)的enclosing作用域润绎。在enclosing作用域的變量對內(nèi)部函數(shù)和外部函數(shù)同時可見撬碟。
例子
def foo():
scope = "enclosed"
def func():
print(scope)
func()
調(diào)用
>> foo()
enclosed
這里我們引入一個關(guān)鍵字nonlocal
,該關(guān)鍵字用于enclosing scope中內(nèi)部函數(shù)修改enclosing變量使用莉撇。
例子
def out():
a = 10
def inside():
nonlocal a
print(f"enclosing variable in the internal function before update: {a}")
a += 99
print(f"enclosing variable in the internal function: {a}")
inside()
print(f"enclosing variable after update by nonlocal keyword: {a}")
返回
>> out()
enclosing variable in the internal function before update: 10
enclosing variable in the internal function: 109
enclosing variable after update by nonlocal keyword: 109
Global scope
global variable在全局作用域(global scope)中聲明(declare)的變量呢蛤,可以被整個程序使用」骼桑可在函數(shù)作用域的內(nèi)其障、外使用使用全局變量。典型的涂佃,全局變量在Python代碼中励翼、函數(shù)外聲明。聲明時可加入關(guān)鍵字global
辜荠,也可不加汽抚。在函數(shù)中調(diào)用全局變量,不可修改侨拦,修改全局變量前需要聲明該全局變量殊橙。
例子
name = "abc"
def foo():
print("Name inside foo() is ", name)
foo()
print("Name outside foo() is :", name)
返回
Name inside foo() is abc
Name outside foo() is : abc
但是如果在函數(shù)內(nèi)部修改調(diào)用的全局變量,則返回錯誤UnboundLocalError
global x
x = 5
def test():
x += 1
return x
調(diào)用
>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in test
UnboundLocalError: local variable 'x' referenced before assignment
如果在修改前聲明其為全局變量狱从,則可以修改
global x
x = 5
def test1():
global x
x += 1
return x
調(diào)用
>> test1()
6
Built-in scope
內(nèi)置作用域是python中可用范圍最廣的作用域膨蛮,包括關(guān)鍵詞(keywords),函數(shù)季研,異常(exceptions)敞葛,以及python內(nèi)置的其他屬性(attributes)。內(nèi)置作用域中的名字在python代碼中均可使用与涡,他們在python程序/腳本運(yùn)行時自動加載惹谐。
例子
>> id('a')
140275629228912
全局變量Global Variable
全局變量可在函數(shù)外定義,是在函數(shù)內(nèi)外都可訪問的變量驼卖。
需要注意的是氨肌,Python中全局變量的作用域?yàn)閙odule內(nèi)部/文件內(nèi)部,即跨文件的全局變量無法互相訪問(?)酌畜≡跚簦互相訪問可能會產(chǎn)生循環(huán)依賴問題(circular import)。
解決方案是將全局變量保存在一個獨(dú)立的文件中桥胞,caller從該文件中import恳守,可避免circular import 問題。例贩虾,創(chuàng)建變量config.py
用于保存全局變量
# config.py
a = 1
b = 'string'
在另一個Python腳本中調(diào)用全局變量
# test.py
import config
print(config.a)
print(config.b)
運(yùn)行
>> python test.py
1
string
Reference
1 stackoverflow
2 知乎
`