函數嵌套及作用域
1.三元運算
if條件成立的結果 if 條件 else 條件不成立的結果
例如:
a=20
b=10
c=a if a>b else b
print(c)
2.命名空間
- 全局命名空間:創建的存儲“變量名與值的關系”的空間叫做全局命名空間
- 局部命名空間:在函數的運行中開辟的臨時的空間叫做局部命名空間
- 內置命名空間:內置命名空間中存放了python解釋器為我們提供的名字:input,print,str,list,tuple...它們都是我們熟悉的,拿過來就可以用的方法。
三種命名空間之間的加載順序和取值順序:
加載順序:內置(程序運行前加載)-->全局(從上到下順序加載進來的)-->局部(調用的時候加載)--->內置
取值:在局部調用:局部命名空間--->全局命名空間--->內置命名空間
站在全局範圍找:全局----內置----局部
使用:
全局不能使用局部的
局部的可以使用全局的
3.作用域:就是作用範圍
1.命名空間和作用域是分不開的
2.作用域分為兩種:
全局作用域:全局命名空間與內置命名空間的名字都屬於全局範圍
在整個文件的任意位置都能被引用,全局有效
局部作用域:局部命名空間,只能在局部範圍內生效
3.站在全局看:
使用名字的時候:如果全局有,用全局的
如果全局沒有,用內置的
4.為什麽要有作用域?
為了函數內的變量不會影響到全局
5.globals方法:查看全局作用域的名字【print(globals())】
locals方法:查看局部作用域的名字【print(locals())】
def func(): a = 12 b = 20 print(locals()) print(globals()) func() 在局部調用locals()和globals()
站在全局看,globals is locals
global關鍵字:強制轉換為全局變量
# x=1 # def foo(): # global x #強制轉換x為全局變量 # x=10000000000 # print(x) # foo() # print(x) # 這個方法盡量能少用就少用 global
nonlocal讓內部函數中的變量在上一層函數中生效,外部必須有
# x=1 # def f1(): # x=2 # def f2(): # # x=3 # def f3(): # # global x#修改全局的 # nonlocal x#修改局部的(當用nonlocal時,修改x=3為x=100000000,當x=3不存在時,修改x=2為100000000 ) # # 必須在函數內部 # x=10000000000 # f3() # print(‘f2內的打印‘,x) # f2() # print(‘f1內的打印‘, x) # f1() # # print(x) nonlocal
4.函數的嵌套定義
def animal(): def tiger(): print(‘nark‘) print(‘eat‘) tiger() animal()
5.作用域鏈
x=1 def heihei(): x=‘h‘ def inner(): x=‘il‘ def inner2(): print(x) inner2() inner() heihei() 函數的作用域鏈
6.函數名的本質:就是函數的內存地址
def func(): print(‘func‘) print(func)#指向了函數的內存地址
7.函數名可以用做函數的參數
#函數名可以用作參數
def func(): print(‘func‘) def func2(f): f() print(‘func2‘) func2(func)
函數名可以作為函數的返回值
return說明1 def func(): def func2(): print(‘func2‘) return func2 f2=func() f2() #func2=func() #func2() 2. def f1(x): print(x) return ‘123‘ def f2(): ret = f1(‘s‘) #f2調用f1函數 print(ret) f2() 3. def func(): def func2(): return ‘a‘ return func2 #函數名作為返回值 func2=func() print(func2())
8.閉包:
閉包:1.閉 :內部的函數
2.包 :包含了對外部函數作用域中變量的引用
def hei():
x=20
def inner():
x=10 #如果x定義了,他就用自己的了,就實現不了閉包
print(x)
# 閉包的常用形式:
def hei():
x=20
def inner():
‘‘‘閉包函數‘‘‘
print(x)
return inner()
判斷閉包函數的方法:__closure__
#輸出的__closure__有cell元素 :是閉包函數 def func(): name = ‘eva‘ def inner(): print(name) print(inner.__closure__) return inner f = func() f() #輸出的__closure__為None :不是閉包函數 name = ‘egon‘ def func2(): def inner(): print(name) print(inner.__closure__) return inner f2 = func2() f2()
閉包獲取網絡網頁
# from urllib.request import urlopen # def index(url): # def inner(): # return urlopen(url).read() # return inner # u=‘http://www.cnblogs.com/Eva-J/articles/7156261.html#_label1‘ # get = index(u) # print(get())
9.總結
作用域:小範圍的可以用大範圍的,但是大範圍的不能用小範圍的
範圍從大到小(圖)
如果在小範圍內,如果要用一個變量,是當前這個小範圍有的,就用自己的
如果在小範圍內沒有,就用上一級的,上一級沒有的,就用上上級的,以此類推
如果都沒有,報錯
10.思維導圖
函數嵌套及作用域