函式作用域

2022-08-21 15:30:15 字數 1346 閱讀 2527

1.python沒有塊級作用域,**快裡的變數,外部可以呼叫

1

if 1 ==1:

2 name = "

qinyanli"3

print

(name)45

for i in range(10):

6 age =i

7print(age)

列印結果為:

qinyanli

9

2.python中的作用域分4種情況:

l:local,區域性作用域,函式中定義的變數

e:enclosing,巢狀的父級函式的區域性作用域,即包含此函式的上級函式的區域性作用域,但不是全域性的。

g:global,全部變數,就是模組級別定義的變數

b:built-in。系統固定模組裡面的變數。比如int,bytearray等。搜尋變數的優先順序順序依次是:legb

1 x  = int(2.5)  #

int 為built in

2 x = 10 #

count = 10 global 全域性作用域

3def

outer():

4 x = 5 #

x = 5 enclosing 作用域

5def

f():

6 x = 3 #

x= 3 local作用域

7print (x)

3.區域性作用域修改全域性作用域,需要加上global +變數名

錯誤**案例:

count = 10

deff():

print

(count)

count = 20f()

執行之後報錯:unboundlocalerror: local variable 'count' referenced before assignmen

正確**案例:

count = 10

deff():

global

count

print

(count)

count = 20f()

執行結果為:10

4.區域性作用域修改enclosing作用域,需要加nonlocal+變數名

def

outer():

count = 20

deff():

nonlocal count

print

(count)

count = 5f()

outer()

執行結果為20

函式作用域

有巢狀函式的時候有return x的返回函式x的位址,沒有的則為none def f1 n1 f1 print f1中 n1 def f2 n2 f2 def f3 n3 f3 print f3中 n3 print f2中 n2 return f3 return f2 r1 f1 print r1 ...

函式作用域

匿名函式,lambda def f o if o 7 print o print list filter lambda o o 8,4,77 22,4 8 list filter f,4,77,22,4,8 列印的話會返回none 77,22 7722 8a 5deff global a 要用全域性...

函式作用域

函式作用域 呼叫函式時建立函式作用域,函式執行完畢以後,函式作用域銷毀 每呼叫一次,函式就會建立乙個新的函式作用域,它們之間是互相獨立的 在函式作用域中,可以訪問到全域性作用域的變數 在全域性作用域中無法訪問到函式作用域的變數 具體示例 當在函式作用域操作乙個變數時,它會先在自身作用域中尋找,如果有...