python学习day-8 迭代器 生成器 装饰器
生活随笔
收集整理的這篇文章主要介紹了
python学习day-8 迭代器 生成器 装饰器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
http://www.cnblogs.com/linhaifeng/articles/7580428.html
迭代器
#迭代器即迭代的工具,那什么是迭代呢?
#迭代是一個重復(fù)的過程,每次重復(fù)即一次迭代,并且每次迭代的結(jié)果都是下一次迭代的初始值
1、為何要有迭代器? 對于序列類型:字符串、列表、元組,我們可以使用索引的方式迭代取出其包含的元素。但對于字典、集合、文件等類型是沒有索引的,若還想取出其內(nèi)部包含的元素,則必須找出一種不依賴于索引的迭代方式,這就是迭代器2、什么是可迭代對象? 可迭代對象指的是內(nèi)置有__iter__方法的對象,即obj.__iter__,如下 'hello'.__iter__ (1,2,3).__iter__ [1,2,3].__iter__ {'a':1}.__iter__ {'a','b'}.__iter__ open('a.txt').__iter__ 3、什么是迭代器對象? 可迭代對象執(zhí)行obj.__iter__()得到的結(jié)果就是迭代器對象 而迭代器對象指的是即內(nèi)置有__iter__又內(nèi)置有__next__方法的對象 文件類型是迭代器對象 open('a.txt').__iter__() open('a.txt').__next__() 4、注意: 迭代器對象一定是可迭代對象,而可迭代對象不一定是迭代器對象
5.用法
dic={'a':1,'b':2,'c':3} iter_dic=dic.__iter__() #得到迭代器對象,迭代器對象即有__iter__又有__next__,但是:迭代器.__iter__()得到的仍然是迭代器本身 iter_dic.__iter__() is iter_dic #True print(iter_dic.__next__()) #等同于next(iter_dic) # print(iter_dic.__next__()) #拋出異常StopIteration,或者說結(jié)束標(biāo)志
6.for循環(huán)
#基于for循環(huán),我們可以完全不再依賴索引去取值了 dic={'a':1,'b':2,'c':3} for k in dic: print(dic[k]) for循環(huán)的工作原理 1:執(zhí)行in后對象的dic.__iter__()方法,得到一個迭代器對象iter_dic 2: 執(zhí)行next(iter_dic),將得到的值賦值給k,然后執(zhí)行循環(huán)體代碼 3: 重復(fù)過程2,直到捕捉到異常StopIteration,結(jié)束循環(huán)
生成器
只要函數(shù)內(nèi)部包含有yield關(guān)鍵字,那么函數(shù)名()的到的結(jié)果就是生成器,并且不會執(zhí)行函數(shù)內(nèi)部代碼
yield相當(dāng)于return 程序就停住了
生成器就是迭代器
三元表達(dá)式
name=input('姓名>>: ') res='SB' if name == 'alex' else 'NB' print(res)
裝飾器
1.高階函數(shù)
2.閉包
3.函數(shù)嵌套
1.函數(shù)閉包
內(nèi)部函數(shù)包含對外部作用域而非全局作用域的引用提示:之前我們都是通過參數(shù)將外部的值傳給函數(shù),閉包提供了另外一種思路,包起來嘍,包起呦,包起來哇
2.函數(shù)嵌套
def father(auth_type):
print('from father %s' %auth_type )
def son():
name='linhaifeng_1'
print('我的爸爸是%s' %name)
def grandson():
print('我的爺爺是%s' %auth_type)
grandson()
son()
father('filedb')
3.高階函數(shù)
'''
高階函數(shù)定義:
1.函數(shù)接收的參數(shù)是一個函數(shù)名
2.函數(shù)的返回值是一個函數(shù)名
3.滿足上述條件任意一個,都可稱之為高階函數(shù)
''' ? 計時加法器
import time
def cal(l):
start_time=time.time()
res=0
for i in l:
time.sleep(0.1)
res+=i
stop_time = time.time()
print('函數(shù)的運(yùn)行時間是%s' %(stop_time-start_time))
return res
print(cal(range(100)))
裝飾器的實現(xiàn)1 import time
def timmer(func): #func=test
def wrapper():
# print(func)
start_time=time.time()
func() #就是在運(yùn)行test()
stop_time = time.time()
print('運(yùn)行時間是%s' %(stop_time-start_time))
return wrapper
@timmer #test=timmer(test)
def test():
time.sleep(3)
print('test函數(shù)運(yùn)行完畢')
test()
# test=timmer(test) #返回的是wrapper的地址
# test() #執(zhí)行的是wrapper()
# @timmer 就相當(dāng)于 test=timmer(test) ?
裝飾器的實現(xiàn)2加上返回值
import time
def timmer(func): #func=test
def wrapper():
start_time=time.time()
res=func() #就是在運(yùn)行test()
stop_time = time.time()
print('運(yùn)行時間是%s' %(stop_time-start_time))
return res
return wrapper
@timmer #test=timmer(test)
def test():
time.sleep(3)
print('test函數(shù)運(yùn)行完畢')
return '這是test的返回值'
res=test() #就是在運(yùn)行wrapper
print(res)
裝飾器的實現(xiàn)3傳入?yún)?shù)
1.
import time
def timmer(func): #func=test1
def wrapper(*args,**kwargs): #test('linhaifeng',age=18) args=('linhaifeng') kwargs={'age':18}
start_time=time.time()
res=func(*args,**kwargs) #就是在運(yùn)行test() func(*('linhaifeng'),**{'age':18})
stop_time = time.time()
print('運(yùn)行時間是%s' %(stop_time-start_time))
return res
return wrapper
@timmer
def test1(name,age,gender):
time.sleep(1)
print('test1函數(shù)運(yùn)行完畢,名字是【%s】 年齡是【%s】 性別【%s】' %(name,age,gender))
return '這是test的返回值'
test1('alex',18,'male')
print(test1('alex',18,'male'))
2.
import time
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time = time.time()
print('函數(shù)運(yùn)行時間是%s' %(stop_time-start_time))
return res
return wrapper
@timmer #相當(dāng)于cal等于timmer(cal)
def cal(l):
res=0
for i in l:
time.sleep(0.1)
res+=i
return res
res=cal(range(20))
print(res) 裝飾器實現(xiàn)帶有參數(shù)驗證功能
user_list=[
{'name':'alex','passwd':'123'},
{'name':'linhaifeng','passwd':'123'},
{'name':'wupeiqi','passwd':'123'},
{'name':'yuanhao','passwd':'123'},
]
current_dic={'username':None,'login':False}
def auth(auth_type='filedb'):
def auth_func(func):
def wrapper(*args,**kwargs):
print('認(rèn)證類型是',auth_type)
if auth_type == 'filedb':
if current_dic['username'] and current_dic['login']:
res = func(*args, **kwargs)
return res
username=input('用戶名:').strip()
passwd=input('密碼:').strip()
for user_dic in user_list:
if username == user_dic['name'] and passwd == user_dic['passwd']:
current_dic['username']=username
current_dic['login']=True
res = func(*args, **kwargs)
return res
else:
print('用戶名或者密碼錯誤')
elif auth_type == 'ldap':
print('鬼才特么會玩')
res = func(*args, **kwargs)
return res
else:
print('鬼才知道你用的什么認(rèn)證方式')
res = func(*args, **kwargs)
return res
return wrapper
return auth_func
@auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')-->@auth_func 附加了一個auth_type --->index=auth_func(index)
def index():
print('歡迎來到京東主頁')
@auth(auth_type='ldap')
def home(name):
print('歡迎回家%s' %name)
#
@auth(auth_type='sssssss')
def shopping_car(name):
print('%s的購物車?yán)镉?#xff3b;%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))
# print('before-->',current_dic)
# index()
# print('after--->',current_dic)
# home('產(chǎn)品經(jīng)理')
shopping_car('產(chǎn)品經(jīng)理')
? ? ?
? ? ?
迭代器
#迭代器即迭代的工具,那什么是迭代呢?
#迭代是一個重復(fù)的過程,每次重復(fù)即一次迭代,并且每次迭代的結(jié)果都是下一次迭代的初始值
1、為何要有迭代器? 對于序列類型:字符串、列表、元組,我們可以使用索引的方式迭代取出其包含的元素。但對于字典、集合、文件等類型是沒有索引的,若還想取出其內(nèi)部包含的元素,則必須找出一種不依賴于索引的迭代方式,這就是迭代器2、什么是可迭代對象? 可迭代對象指的是內(nèi)置有__iter__方法的對象,即obj.__iter__,如下 'hello'.__iter__ (1,2,3).__iter__ [1,2,3].__iter__ {'a':1}.__iter__ {'a','b'}.__iter__ open('a.txt').__iter__ 3、什么是迭代器對象? 可迭代對象執(zhí)行obj.__iter__()得到的結(jié)果就是迭代器對象 而迭代器對象指的是即內(nèi)置有__iter__又內(nèi)置有__next__方法的對象 文件類型是迭代器對象 open('a.txt').__iter__() open('a.txt').__next__() 4、注意: 迭代器對象一定是可迭代對象,而可迭代對象不一定是迭代器對象
5.用法
dic={'a':1,'b':2,'c':3} iter_dic=dic.__iter__() #得到迭代器對象,迭代器對象即有__iter__又有__next__,但是:迭代器.__iter__()得到的仍然是迭代器本身 iter_dic.__iter__() is iter_dic #True print(iter_dic.__next__()) #等同于next(iter_dic) # print(iter_dic.__next__()) #拋出異常StopIteration,或者說結(jié)束標(biāo)志
6.for循環(huán)
#基于for循環(huán),我們可以完全不再依賴索引去取值了 dic={'a':1,'b':2,'c':3} for k in dic: print(dic[k]) for循環(huán)的工作原理 1:執(zhí)行in后對象的dic.__iter__()方法,得到一個迭代器對象iter_dic 2: 執(zhí)行next(iter_dic),將得到的值賦值給k,然后執(zhí)行循環(huán)體代碼 3: 重復(fù)過程2,直到捕捉到異常StopIteration,結(jié)束循環(huán)
生成器
只要函數(shù)內(nèi)部包含有yield關(guān)鍵字,那么函數(shù)名()的到的結(jié)果就是生成器,并且不會執(zhí)行函數(shù)內(nèi)部代碼
yield相當(dāng)于return 程序就停住了
生成器就是迭代器
三元表達(dá)式
name=input('姓名>>: ') res='SB' if name == 'alex' else 'NB' print(res)
裝飾器
1.高階函數(shù)
2.閉包
3.函數(shù)嵌套
1.函數(shù)閉包
內(nèi)部函數(shù)包含對外部作用域而非全局作用域的引用提示:之前我們都是通過參數(shù)將外部的值傳給函數(shù),閉包提供了另外一種思路,包起來嘍,包起呦,包起來哇
2.函數(shù)嵌套
def father(auth_type):
print('from father %s' %auth_type )
def son():
name='linhaifeng_1'
print('我的爸爸是%s' %name)
def grandson():
print('我的爺爺是%s' %auth_type)
grandson()
son()
father('filedb')
3.高階函數(shù)
'''
高階函數(shù)定義:
1.函數(shù)接收的參數(shù)是一個函數(shù)名
2.函數(shù)的返回值是一個函數(shù)名
3.滿足上述條件任意一個,都可稱之為高階函數(shù)
''' ? 計時加法器
import time
def cal(l):
start_time=time.time()
res=0
for i in l:
time.sleep(0.1)
res+=i
stop_time = time.time()
print('函數(shù)的運(yùn)行時間是%s' %(stop_time-start_time))
return res
print(cal(range(100)))
裝飾器的實現(xiàn)1 import time
def timmer(func): #func=test
def wrapper():
# print(func)
start_time=time.time()
func() #就是在運(yùn)行test()
stop_time = time.time()
print('運(yùn)行時間是%s' %(stop_time-start_time))
return wrapper
@timmer #test=timmer(test)
def test():
time.sleep(3)
print('test函數(shù)運(yùn)行完畢')
test()
# test=timmer(test) #返回的是wrapper的地址
# test() #執(zhí)行的是wrapper()
# @timmer 就相當(dāng)于 test=timmer(test) ?
裝飾器的實現(xiàn)2加上返回值
import time
def timmer(func): #func=test
def wrapper():
start_time=time.time()
res=func() #就是在運(yùn)行test()
stop_time = time.time()
print('運(yùn)行時間是%s' %(stop_time-start_time))
return res
return wrapper
@timmer #test=timmer(test)
def test():
time.sleep(3)
print('test函數(shù)運(yùn)行完畢')
return '這是test的返回值'
res=test() #就是在運(yùn)行wrapper
print(res)
裝飾器的實現(xiàn)3傳入?yún)?shù)
1.
import time
def timmer(func): #func=test1
def wrapper(*args,**kwargs): #test('linhaifeng',age=18) args=('linhaifeng') kwargs={'age':18}
start_time=time.time()
res=func(*args,**kwargs) #就是在運(yùn)行test() func(*('linhaifeng'),**{'age':18})
stop_time = time.time()
print('運(yùn)行時間是%s' %(stop_time-start_time))
return res
return wrapper
@timmer
def test1(name,age,gender):
time.sleep(1)
print('test1函數(shù)運(yùn)行完畢,名字是【%s】 年齡是【%s】 性別【%s】' %(name,age,gender))
return '這是test的返回值'
test1('alex',18,'male')
print(test1('alex',18,'male'))
2.
import time
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time = time.time()
print('函數(shù)運(yùn)行時間是%s' %(stop_time-start_time))
return res
return wrapper
@timmer #相當(dāng)于cal等于timmer(cal)
def cal(l):
res=0
for i in l:
time.sleep(0.1)
res+=i
return res
res=cal(range(20))
print(res) 裝飾器實現(xiàn)帶有參數(shù)驗證功能
user_list=[
{'name':'alex','passwd':'123'},
{'name':'linhaifeng','passwd':'123'},
{'name':'wupeiqi','passwd':'123'},
{'name':'yuanhao','passwd':'123'},
]
current_dic={'username':None,'login':False}
def auth(auth_type='filedb'):
def auth_func(func):
def wrapper(*args,**kwargs):
print('認(rèn)證類型是',auth_type)
if auth_type == 'filedb':
if current_dic['username'] and current_dic['login']:
res = func(*args, **kwargs)
return res
username=input('用戶名:').strip()
passwd=input('密碼:').strip()
for user_dic in user_list:
if username == user_dic['name'] and passwd == user_dic['passwd']:
current_dic['username']=username
current_dic['login']=True
res = func(*args, **kwargs)
return res
else:
print('用戶名或者密碼錯誤')
elif auth_type == 'ldap':
print('鬼才特么會玩')
res = func(*args, **kwargs)
return res
else:
print('鬼才知道你用的什么認(rèn)證方式')
res = func(*args, **kwargs)
return res
return wrapper
return auth_func
@auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')-->@auth_func 附加了一個auth_type --->index=auth_func(index)
def index():
print('歡迎來到京東主頁')
@auth(auth_type='ldap')
def home(name):
print('歡迎回家%s' %name)
#
@auth(auth_type='sssssss')
def shopping_car(name):
print('%s的購物車?yán)镉?#xff3b;%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))
# print('before-->',current_dic)
# index()
# print('after--->',current_dic)
# home('產(chǎn)品經(jīng)理')
shopping_car('產(chǎn)品經(jīng)理')
? ? ?
? ? ?
轉(zhuǎn)載于:https://www.cnblogs.com/wangxiaoyienough/p/9265362.html
總結(jié)
以上是生活随笔為你收集整理的python学习day-8 迭代器 生成器 装饰器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 乐观锁、悲观锁简单分析,回忆旧(新)知识
- 下一篇: 微信小程序朋友圈分享图片生成方案实现