一、函數對象 |
函數對象:函數是第一類對象,即函數可以當作數據傳遞
1 可以被引用
2 可以當作參數傳遞
3 返回值可以是函數
3 可以當作容器類型的元素
1、函數可以被引用,即函數可以賦值給一個變量

1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 def foo(): 4 print('from foo') 5 6 foo() 7 func=foo #引用,賦值 8 print(foo) 9 print(func) 10 func()
2、可以當作參數傳遞
1 def foo(): 2 print('from foo') 3 4 def bar(func): 5 print(func) 6 func() 7 8 bar(foo) 9 10 代碼運行結果: 11 <function foo at 0x1047eff28> 12 from foo
3、返回值可以是函數
1 def foo(): 2 print('from foo') 3 4 def bar(func): 5 return func 6 7 f=bar(foo) 8 9 print(f) 10 11 f() 12 13 運行結果: 14 <function foo at 0x0000024AD6E48AE8> 15 from foo
4、可以當作容器類型的元素
1 def foo(): 2 print('from foo') 3 dic={'func':foo} 4 5 print(dic['func']) 6 7 dic['func']() 8 9 運行結果: 10 <function foo at 0x0000020849BE8AE8> 11 from foo
5、函數可以嵌套
1 def f1(): 2 3 def f2(): 4 print('from f2') 5 def f3(): 6 print('from f3') 7 f3() 8 f2() 9 10 11 f1() 12 13 14 運行結果: 15 from f2 16 from f3
二、函數的命名空間和作用域 |
函數有三種命名空間
1、內置命名空間,隨着python解釋器的啟動而產生
print(sum) print(max) print(min) print(max([1,2,3])) import builtins for i in dir(builtins): print(i)
2、全局名稱空間:文件的執行會產生全局名稱空間,指的是文件級別定義的名字都會放入該空間
1 x=1 2 3 4 def func(): 5 money=2000 6 x=2 7 print('func') 8 print(x) 9 print(func) 10 func() 11 print(money) 12 13 func() 14 print(x)
3、局部名稱空間:調用函數時會產生局部名稱空間,只在函數調用時臨時綁定,調用結束解綁定
1 x=10000 2 def func(): 3 x=1 4 def f1(): 5 pass
作用域
1. 全局作用域:內置名稱空間,全局名層空間
2. 局部作用:局部名稱空間
名字的查找順序:局部名稱空間---》全局名層空間---》內置名稱空間
1 # x=1 2 def func(): 3 # x=2 4 # print(x) 5 # sum=123123 6 print(sum) 7 func()
查看全局作用域內的名字:gloabls()
查看局局作用域內的名字:locals()
1 x=1000 2 def func(): 3 x=2 4 5 print(globals()) 6 7 print(locals()) 8 print(globals() is locals())
全局作用域:全局有效,在任何位置都能被訪問到,除非del刪掉,否則會一直存活到文件執行完畢
局部作用域的名字:局部有效,只能在局部范圍調用,只在函數調用時才有效,調用結束就失效
1 x=1 2 3 def f1(): 4 print(x) 5 6 def foo(): 7 print(x) 8 9 def f(x): 10 # x=4 11 def f2(): 12 # x=3 13 def f3(): 14 # x=2 15 print(x) 16 17 f3() 18 f2() 19 20 f(4)
閉包函數 |
閉包函數是指延伸了作用域的函數,其中包含函數定義體中引用,但是不在定義體中定義的非全局變量,它能夠訪問定義體之外定義的非全局變量
簡單來說,一個閉包就是你調用了一個函數A,這個函數A返回了一個函數B給你。這個返回的函數B就叫做閉包。
閉包函數須滿足以下條件:
1. 定義在內部函數;
2. 包含對外部作用域而非全局作用域的引用;
例子:
1 def f1(): 2 x = 1 3 def f2(): 4 print(x) 5 return f2 6 7 f=f1() 8 print(f) 9 10 x=100 11 f() 12 print(x)
結果:
1 <function f1.<locals>.f2 at 0x000001F1B70B89D8> 2 1 3 100
閉包的應用:惰性計算
from urllib.request import urlopen def index(url): def get(): return urlopen(url).read() return get oldboy=index('http://crm.oldboyedu.com') print(oldboy().decode('utf-8')) print(oldboy.__closure__[0].cell_contents)
裝飾器 |
實現並發效果
1、定義:
裝飾器:修飾別人的工具,修飾添加功能,工具指的是函數
裝飾器本身可以是任何可調用對象,被裝飾的對象也可以是任意可調用對象
2、為什么要用裝飾器:
開放封閉原則:對修改是封閉的,對擴展是開放的3、裝飾器的基本框架
裝飾器就是為了在不修改被裝飾對象的源代碼以及調用方式的前提下,為期添加新功能
1 def timer(func): 2 def wrapper(): 3 func() 4 return wrapper 5 6 @timer 7 def index(): 8 print(welcome) 9 10 index() 11 12 13 # 帶參數的 14 def timer(func): 15 def wrapper(*args,**kwargs): 16 func(*args,**kwargs) 17 return wrapper 18 19 @timer # index=timer(index) 20 def index(name): # index =wrapper 21 print(name) 22 23 index('hehe')
4、裝飾器的實現
裝飾器的功能是將被裝飾的函數當作參數傳遞給與裝飾器對應的函數(名稱相同的函數),並返回包裝后的被裝飾的函數”
1 def a(name): #與裝飾器對應的函數 2 return name() 3 4 @a #裝飾器的作用是 b = a(b) 5 def b(): #被裝飾函數 6 print('welcome')
實現二:
1 import time 2 3 def timmer(func): 4 def wrapper(*args,**kwargs): 5 start_time=time.time() 6 res=func(*args,**kwargs) 7 stop_time=time.time() 8 print('run time is %s' %(stop_time-start_time)) 9 return wrapper 10 11 @timmer #index=timmer(index)==>index=wrapper==> 12 def index(): # index=wrapper 13 14 time.sleep(3) 15 print('welcome to index') 16 17 index()
代碼終極實現講解

1 # import time 2 # 3 # def timmer(func): 4 # def wrapper(*args,**kwargs): 5 # start_time=time.time() 6 # res=func(*args,**kwargs) 7 # stop_time=time.time() 8 # print('run time is %s' %(stop_time-start_time)) 9 # return wrapper 10 # 11 # @timmer 12 # def index(): 13 # 14 # time.sleep(3) 15 # print('welcome to index') 16 # 17 # index() 18 19 20 21 # import time 22 # 23 # def timmer(func): 24 # def wrapper(): 25 # start_time=time.time() 26 # func() #index() 27 # stop_time=time.time() 28 # print('run time is %s' %(stop_time-start_time)) 29 # return wrapper 30 # 31 # 32 # @timmer #index=timmer(index) 33 # def index(): 34 # time.sleep(3) 35 # print('welcome to index') 36 # 37 # 38 # # f=timmer(index) 39 # # # print(f) 40 # # f() #wrapper()---->index() 41 # 42 # # index=timmer(index) #index==wrapper 43 # 44 # index() #wrapper()-----> 45 46 47 48 #流程分析 49 # import time 50 # def timmer(func): 51 # def wrapper(): 52 # start_time=time.time() 53 # func() 54 # stop_time=time.time() 55 # print('run time is %s' %(stop_time-start_time)) 56 # return wrapper 57 # 58 # @timmer #index=timmer(index) 59 # def index(): 60 # time.sleep(3) 61 # print('welcome to index') 62 # 63 # 64 # index() #wrapper() 65 66 67 68 69 70 71 72 73 # import time 74 # def timmer(func): 75 # def wrapper(*args,**kwargs): 76 # start_time=time.time() 77 # res=func(*args,**kwargs) 78 # stop_time=time.time() 79 # print('run time is %s' %(stop_time-start_time)) 80 # return res 81 # return wrapper 82 # 83 # @timmer #index=timmer(index) 84 # def index(): 85 # time.sleep(3) 86 # print('welcome to index') 87 # return 1 88 # 89 # @timmer 90 # def foo(name): 91 # time.sleep(1) 92 # print('from foo') 93 # 94 # 95 # res=index() #wrapper() 96 # print(res) 97 # 98 # res1=foo('egon') #res1=wrapper('egon') 99 # print(res1) 100 # 101 # 102 103 # def auth(func): 104 # def wrapper(*args,**kwargs): 105 # name=input('>>: ') 106 # password=input('>>: ') 107 # if name == 'egon' and password == '123': 108 # print('\033[45mlogin successful\033[0m') 109 # res=func(*args,**kwargs) 110 # return res 111 # else: 112 # print('\033[45mlogin err\033[0m') 113 # return wrapper 114 # 115 # 116 # 117 # @auth 118 # def index(): 119 # print('welcome to index page') 120 # @auth 121 # def home(name): 122 # print('%s welcome to home page' %name) 123 # 124 # index() 125 # home('egon') 126 # 127 128 129 # login_user={'user':None,'status':False} 130 # def auth(func): 131 # def wrapper(*args,**kwargs): 132 # if login_user['user'] and login_user['status']: 133 # res=func(*args,**kwargs) 134 # return res 135 # else: 136 # name=input('>>: ') 137 # password=input('>>: ') 138 # if name == 'egon' and password == '123': 139 # login_user['user']='egon' 140 # login_user['status']=True 141 # print('\033[45mlogin successful\033[0m') 142 # res=func(*args,**kwargs) 143 # return res 144 # else: 145 # print('\033[45mlogin err\033[0m') 146 # return wrapper 147 # 148 # @auth 149 # def index(): 150 # print('welcome to index page') 151 # @auth 152 # def home(name): 153 # print('%s welcome to home page' %name) 154 # index() 155 # home('egon')
迭代器 |
可以被next()函數調用並
1、迭代的概念:
重復+上一次迭代的結果為下一次迭代的初始值
重復的過程稱為迭代,每次重復即一次迭代,
並且每次迭代的結果是下一次迭代的初始值
不斷返回下一個值的對象稱為迭代器:Iterator。
這些可以直接作用於for循環的對象統稱為可迭代對象:Iterable
生成器都是迭代器,因為生成器有next方法,迭代器不一定是生成器。
2、為什么要有迭代器
#為什么要有迭代器?對於沒有索引的數據類型,必須提供一種不依賴索引的迭代方式
#可迭代的對象:內置__iter__方法的,都是可迭代的對象
3、迭代器的優缺點:
優點:
1.提供了一種不依賴下標的迭代方式
2.就跌迭代器本身來說,更節省內存
缺點:
1. 無法獲取迭代器對象的長度
2. 不如序列類型取值靈活,是一次性的,只能往后取值,不能往前退
4、迭代器的實現
1 l = [1, 2, 3] 2 count = 0 3 while count < len(l): # 只滿足重復,因而不是迭代 4 print('====>', l[count]) 5 count += 1 6 7 l = (1, 2, 3) 8 count = 0 9 while count < len(l): # 只滿足重復,因而不是迭代 10 print('====>', l[count]) 11 count += 1 12 13 s='hello' 14 count = 0 15 while count < len(s): 16 print('====>', s[count]) 17 count += 1

1 #為什么要有迭代器?對於沒有索引的數據類型,必須提供一種不依賴索引的迭代方式 2 3 #可迭代的對象:內置__iter__方法的,都是可迭代的對象 4 5 [1,2].__iter__() 6 'hello'.__iter__() 7 (1,2).__iter__() 8 9 {'a':1,'b':2}.__iter__() 10 {1,2,3}.__iter__() 11 12 #迭代器:執行__iter__方法,得到的結果就是迭代器,迭代器對象有__next__方法 13 i=[1,2,3].__iter__() 14 15 print(i) 16 17 print(i.__next__()) 18 print(i.__next__()) 19 print(i.__next__()) 20 print(i.__next__()) #拋出異常:StopIteration 21 22 23 i={'a':1,'b':2,'c':3}.__iter__() 24 25 print(i.__next__()) 26 print(i.__next__()) 27 print(i.__next__()) 28 print(i.__next__()) 29 30 dic={'a':1,'b':2,'c':3} 31 i=dic.__iter__() 32 while True: 33 try: 34 key=i.__next__() 35 print(dic[key]) 36 except StopIteration: 37 break 38 39 40 41 s='hello' 42 print(s.__len__()) 43 44 print(len(s)) 45 46 len(s)====== s.__len__() 47 48 49 s={'a',3,2,4} 50 51 s.__iter__() #iter(s) 52 53 i=iter(s) 54 print(next(i)) 55 print(next(i)) 56 print(next(i)) 57 print(next(i)) 58 print(next(i)) 59 60 61 #如何判斷一個對象是可迭代的對象,還是迭代器對象 62 from collections import Iterable,Iterator 63 64 'abc'.__iter__() 65 ().__iter__() 66 [].__iter__() 67 {'a':1}.__iter__() 68 {1,2}.__iter__() 69 70 f=open('a.txt','w') 71 f.__iter__() 72 73 74 #下列數據類型都是可迭代的對象 75 print(isinstance('abc',Iterable)) 76 print(isinstance([],Iterable)) 77 print(isinstance((),Iterable)) 78 print(isinstance({'a':1},Iterable)) 79 print(isinstance({1,2},Iterable)) 80 print(isinstance(f,Iterable)) 81 82 83 84 #只有文件是迭代器對象 85 print(isinstance('abc',Iterator)) 86 print(isinstance([],Iterator)) 87 print(isinstance((),Iterator)) 88 print(isinstance({'a':1},Iterator)) 89 print(isinstance({1,2},Iterator)) 90 print(isinstance(f,Iterator)) 91 92 93 ''' 94 可迭代對象:只有__iter__方法,執行該方法得到的迭代器對象 95 96 迭代協議: 97 對象有__next__ 98 對象有__iter__,對於迭代器對象來說,執行__iter__方法,得到的結果仍然是它本身 99 100 101 ''' 102 f1=f.__iter__() 103 104 print(f) 105 print(f1) 106 print(f is f1) 107 108 109 l=[] 110 i=l.__iter__() 111 112 print(i.__iter__()) 113 print(i) 114 print(l) 115 116 117 dic={'name':'egon','age':18,'height':'180'} 118 print(dic.items()) 119 120 for k,v in dic.items(): 121 print(k,v) 122 123 i=iter(dic) 124 while True: 125 try: 126 k=next(i) 127 print(k) 128 except StopIteration: 129 break 130 for k in dic: #i=iter(dic) k=next(i) 131 print(k) 132 print(dic[k]) 133 134 135 136 137 l=['a','b',3,9,10] 138 for i in l: 139 print(i) 140 141 142 143 with open('a.txt','r',encoding='utf-8') as f: 144 for line in f: 145 print(line) 146 print(next(f)) 147 print(next(f)) 148 print(next(f)) 149 print(next(f)) 150 print(next(f)) 151 print(next(f)) 152 print(next(f)) 153 print(next(f))
內置函數 |
all print (all([1,-5,3]))
any print (any([1,-5,3]))

bin(255) ——>十進制轉二進制
4、bool 判斷真假
5、byte array 可修改的二進制格式 字符串不能修改、元祖不能修改
6、call
7、chr chr(97) 把數字對應的ascii碼返回
8、ord ord(‘a’) 把字母對應的ascii碼數字返回
9、compile 用於把代碼進行編譯
10、dived divmod(5,3)
11、eval
12、exec
匿名函數 |
filter 過濾后合格的打印
map 傳參數,並賦值打印結果
reduce
import functools
functors.reduce

如上圖:lambda x:x[1]是按照value排序的。
x 是所以的元素x[1]取value的值

Json |
序列化 json.dumps()
反序列號 json.loads()
jason只能處理簡單的。如果需要在函數中使用處理序列化,需要picle。picle只能在python本語言使用。
目錄結構 |

同級目錄導入
