python函數名的應用、閉包和叠代器
阿新 • • 發佈:2018-08-10
index tun 容器類 c51 sub getattr 技術 del getitem
一、函數名的應用(第一類對象)
函數名是一個變量,但它是一個特殊的變量,與括號配合可以執行函數變量。
1.函數名的內存地址
def func(): print("哈哈") print(func) #<function func at 0x000002750A7998C8>
2.函數名可以賦值給其他變量
def func(): print("哈哈") print(func) a = func #把函數當成一個變量賦值給另一個變量 a() #函數調用 func() #<function func at 0x00000211E56198C8> #哈哈
3.函數名可以當做容器類的元素
def func1(): print("哈哈") def func2(): print("哈哈") def func3(): print("哈哈") def func4(): print("哈哈") lst = [func1,func2,func3] for i in lst: i() # 哈哈 # 哈哈 # 哈哈View Code
4.函數名可以當函數的參數
def func(): print("吃了麽") def func2(fn): print("我是func2") fn() print("我是func2View Code") func2(func) #把函數func當成參數傳遞給func2的參數fu # 我是func2 # 吃了麽 # 我是func2
5.函數名可以當作函數的返回值
def func_1(): print("這裏是函數1") def func_2(): print("這裏是函數2") print("這裏是函數1") return func_2 fn = func_1() #執行函數1,函數1返回的是函數2,這時fn指向的就是上面的函數2 fn() #執行上面返回的函數 #View Code這裏是函數1 # 這裏是函數1 # 這裏是函數2
二、閉包
閉包:在內層函數中訪問外層函數的局部變量
優點:
1保護你的變量不受外界影響
2.可以讓變量常駐內存
寫法:
def outer():
a = 10
def inner():
print(a)
retunt inner
判斷方法:
def func(): a = 10 def inner(): print(a) print(inner.__closure__) # 如果打印的是None. 不是閉包. 如果不是None, 就是閉包 func()
三、叠代器
使用dir來查看該數據包含了哪些方法
print(dir(str)) #結果 [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]View Code
用來遍歷列表,字符串,元組...等等可叠代對象
可叠代對象:Iterable,裏面有__iter__()可以獲取叠代器,沒有__next__()
叠代器: Iterable,裏面有__iter__()可以獲取叠代器,還有__next__()
叠代器的特點:
1.只能向前
2.惰性機制
3.省內存(生成器)
for循環的內部機制
1.首先獲取到叠代器
2.使用while循環獲取數據
3.it.__next__()來獲取數據
4.處理異常 try:xxx except StopIteration:
s = "我是一名小畫家" it = s.__iter__() while 1: try: el = it.__next__() print(el) except StopIteration: break # 我 # 是 # 一 # 名 # 小 # 畫 # 家View Code
判斷方法:
s = "abc" it = s.__iter__() #第一種方法 print("__iter__" in dir(it)) #輸出是Ture說明是可叠代對象 print("__next__" in dir(it)) #輸出是Ture說明是叠代器 #第二種方法 from collections import Iterable from collections import Iterator print(isinstance(it,Iterable)) #判斷是不是可叠代對象 print(isinstance(it,Iterator)) #判斷是不是叠代器View Code
python函數名的應用、閉包和叠代器