python生成器、迭代器、__call__、闭包简单说明
1.生成器
這種一邊循環一邊計算的機制,稱為生成器:generator,最簡單的方法是把生成式的[]改為().
>>> l=(x * x for x in range(1, 11) if x % 2 == 0) >>> l <generator object <genexpr> at 0x7fb6ca32fca8> 定義生成器的另一種方法:如果一個函數定義中包含yield關鍵字, 那么這個函數就不再是一個普通函數,而是一個生成器: def fib(max):n, a, b = 0, 0, 1while n < max:yield ba, b = b, a+bn += 1return 'done' 任何一個循環都得有一個結束條件,n在這個函數中就是結束條件, b是主角a是配角,循環一次生成器就改變一次.2.迭代器
凡是可作用于for循環的對象都是Iterable類型(可迭代對象); 凡是可作用于next()函數的對象都是Iterator類型;它們表示一個惰性計算的序列; 集合數據類型如list、dict、str等是Iterable但不是Iterator, 不過可以通過iter()函數獲得一個Iterator對象; Python的for循環本質上就是通過不斷調用next()函數實現的.3.在頁腳html代碼添加如下內容,會增加打賞功能:
<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.在頁首html代碼添加如下代碼,右上角會出現藏著github地址的a標簽圖片:
<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__ 方法
實現了__call__方法的對象,相當于重載了(),可以實現調用功能.
class A():def __call__(self,name):print("%s is running!" % name) >>> a = A() >>> a("people") people is running!實現斐波納契數列的類:
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.部署完一個網站后,想統計用戶總訪問量、日訪問量、用戶ip地址和該ip地址的訪問次數,
定義一個函數,也可以是裝飾器,在視圖中調用,
這種做法只適合簡單頁面訪問量統計,不適合統計高并發頁面訪問量,而且會降低性能,
等以后水平高了再來想這個問題.
參考地址:https://blog.csdn.net/Duke10/article/details/81273741
Django2.0整合markdown編輯器并實現代碼高亮
參考地址:https://blog.csdn.net/Duke10/article/details/81033686
7.閉包
閉包:在一個外函數中定義了一個內函數,內函數里運用了外函數的臨時變量,
并且外函數的返回值是內函數的引用,這樣就構成了一個閉包.
def test(number):print("--1--")def test_in(number2):print("--2--")print(number + number2)print("--3--")return test_inret = test(100) ret(1)?
轉載于:https://www.cnblogs.com/fawaikuangtu123/p/9981379.html
總結
以上是生活随笔為你收集整理的python生成器、迭代器、__call__、闭包简单说明的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 文件与文件夹课后作业
- 下一篇: python 字典添加元素