python生成器、迭代器、__call__、闭包简单说明
1.生成器
這種一邊循環(huán)一邊計(jì)算的機(jī)制,稱為生成器:generator,最簡(jiǎn)單的方法是把生成式的[]改為().
>>> l=(x * x for x in range(1, 11) if x % 2 == 0) >>> l <generator object <genexpr> at 0x7fb6ca32fca8> 定義生成器的另一種方法:如果一個(gè)函數(shù)定義中包含yield關(guān)鍵字, 那么這個(gè)函數(shù)就不再是一個(gè)普通函數(shù),而是一個(gè)生成器: def fib(max):n, a, b = 0, 0, 1while n < max:yield ba, b = b, a+bn += 1return 'done' 任何一個(gè)循環(huán)都得有一個(gè)結(jié)束條件,n在這個(gè)函數(shù)中就是結(jié)束條件, b是主角a是配角,循環(huán)一次生成器就改變一次.2.迭代器
凡是可作用于for循環(huán)的對(duì)象都是Iterable類型(可迭代對(duì)象); 凡是可作用于next()函數(shù)的對(duì)象都是Iterator類型;它們表示一個(gè)惰性計(jì)算的序列; 集合數(shù)據(jù)類型如list、dict、str等是Iterable但不是Iterator, 不過(guò)可以通過(guò)iter()函數(shù)獲得一個(gè)Iterator對(duì)象; Python的for循環(huán)本質(zhì)上就是通過(guò)不斷調(diào)用next()函數(shù)實(shí)現(xiàn)的.3.在頁(yè)腳html代碼添加如下內(nèi)容,會(huì)增加打賞功能:
<script>window.tctipConfig = {staticPrefix: "http://static.tctip.com",buttonImageId: 5,buttonTip: "zanzhu",list:{alipay: { qrimg: "https://files.cnblogs.com/files/fawaikuangtu123/weichat.bmp"}, //修改1weixin: { qrimg: "https://files.cnblogs.com/files/fawaikuangtu123/zfb.bmp"}, //修改2}}; </script>4.在頁(yè)首html代碼添加如下代碼,右上角會(huì)出現(xiàn)藏著github地址的a標(biāo)簽圖片:
<a href="https://github.com/LiXiang-LiXiang" title="Fork me on GitHub" target="_blank"> <img style="position: absolute; top: 72px; right: 1px; border: 0" alt="Fork me on GitHub" src="http://images.cnblogs.com/cnblogs_com/fawaikuangtu123/1343168/o_Fuck-me-on-GitHub.png"></a>5.Python __call__ 方法
實(shí)現(xiàn)了__call__方法的對(duì)象,相當(dāng)于重載了(),可以實(shí)現(xiàn)調(diào)用功能.
class A():def __call__(self,name):print("%s is running!" % name) >>> a = A() >>> a("people") people is running!實(shí)現(xiàn)斐波納契數(shù)列的類:
class Fib(object):def __call__(self, *args, **kwargs):ret = [1,1]num = int(args[0])if num == 1:return [1, ]else:while len(ret) < num:ret.append(ret[-1] + ret[-2])return ret hehe = Fib() print(hehe(5))6.部署完一個(gè)網(wǎng)站后,想統(tǒng)計(jì)用戶總訪問(wèn)量、日訪問(wèn)量、用戶ip地址和該ip地址的訪問(wèn)次數(shù),
定義一個(gè)函數(shù),也可以是裝飾器,在視圖中調(diào)用,
這種做法只適合簡(jiǎn)單頁(yè)面訪問(wèn)量統(tǒng)計(jì),不適合統(tǒng)計(jì)高并發(fā)頁(yè)面訪問(wèn)量,而且會(huì)降低性能,
等以后水平高了再來(lái)想這個(gè)問(wèn)題.
參考地址:https://blog.csdn.net/Duke10/article/details/81273741
Django2.0整合markdown編輯器并實(shí)現(xiàn)代碼高亮
參考地址:https://blog.csdn.net/Duke10/article/details/81033686
7.閉包
閉包:在一個(gè)外函數(shù)中定義了一個(gè)內(nèi)函數(shù),內(nèi)函數(shù)里運(yùn)用了外函數(shù)的臨時(shí)變量,
并且外函數(shù)的返回值是內(nèi)函數(shù)的引用,這樣就構(gòu)成了一個(gè)閉包.
def test(number):print("--1--")def test_in(number2):print("--2--")print(number + number2)print("--3--")return test_inret = test(100) ret(1)?
轉(zhuǎn)載于:https://www.cnblogs.com/fawaikuangtu123/p/9981379.html
總結(jié)
以上是生活随笔為你收集整理的python生成器、迭代器、__call__、闭包简单说明的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 文件与文件夹课后作业
- 下一篇: python 字典添加元素