[Python] 函式進階⑶——內建函式和匿名函式
函式進階⑶
內建函式
我們一起來看看python裡的內建函式。什麼是內建函式?就是Python給你提供的,拿來直接用的函式,比如print,input等等。截止到python版本3.6.2,現在python一共為我們提供了68個內建函式。它們就是python提供給你直接可以拿來使用的所有函式。這些函式有些我們已經用過了,有些我們還沒用到過,還有一些是被封印了,必須等我們學了新知識才能解開封印的。那今天我們就一起來認識一下python的內建函式。這麼多函式,我們該從何學起呢?
內建函式 | ||||
abs() | dict() | help() | min() | setattr() |
all() | dir() | hex() | next() | slice() |
any() | divmod() | id() | object() | sorted() |
ascii() | enumerate() | input() | oct() | staticmethod() |
bin() | eval() | int() | open() | str() |
bool() | exec() | isinstance() | ord() | sum() |
bytearray() | filter() | issubclass() | pow() | super() |
bytes() | float() | iter() | print() | tuple() |
callable() | format() | len() | property() | type() |
chr() | frozenset() | list() | range() | vars() |
classmethod() | getattr() | locals() | repr() | zip() |
compile() | globals() | map() | reversed() | __import__() |
complex() | hasattr() | max() | round() | |
delattr() | hash() | memoryview() | set() |
1.1作用域相關
locals :函式會以字典的型別返回當前位置的全部區域性變數。
globals:函式以字典的型別返回全部全域性變數。
a = 1 b = 2 print(locals()) print(globals()) # 這兩個一樣,因為是在全域性執行的。########################## def func(argv): c = 2 print(locals()) print(globals()) func(3) #這兩個不一樣,locals() {'argv': 3, 'c': 2} #globals() {'__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>, '__spec__': None, '__file__': 'D:/lnh.python/.../內建函式.py', 'func': <function func at 0x0000024408CF90D0>, '__name__': '__main__', '__package__': None}
1.2其他相關
1.2.1 字串型別程式碼的執行 eval,exec,complie
eval:執行字串型別的程式碼,並返回最終結果。
eval('2 + 2') # 4 n=81 eval("n + 4") # 85 eval('print(666)') # 666
exec:執行字串型別的程式碼。
s = ''' for i in [1,2,3]: print(i) ''' exec(s)
compile:將字串型別的程式碼編譯。程式碼物件能夠通過exec語句來執行或者eval()進行求值。
''' 引數說明: 1. 引數source:字串或者AST(Abstract Syntax Trees)物件。即需要動態執行的程式碼段。 2. 引數 filename:程式碼檔名稱,如果不是從檔案讀取程式碼則傳遞一些可辨認的值。當傳入了source引數時,filename引數傳入空字元即可。 3. 引數model:指定編譯程式碼的種類,可以指定為 ‘exec’,’eval’,’single’。當source中包含流程語句時,model應指定為‘exec’;當source中只包含一個簡單的求值表示式,model應指定為‘eval’;當source中包含了互動式命令語句,model應指定為'single'。 ''' >>> #流程語句使用exec >>> code1 = 'for i in range(0,10): print (i)' >>> compile1 = compile(code1,'','exec') >>> exec (compile1) >>> #簡單求值表示式用eval >>> code2 = '1 + 2 + 3 + 4' >>> compile2 = compile(code2,'','eval') >>> eval(compile2) >>> #互動語句用single >>> code3 = 'name = input("please input your name:")' >>> compile3 = compile(code3,'','single') >>> name #執行前name變數不存在 Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> name NameError: name 'name' is not defined >>> exec(compile3) #執行時顯示互動命令,提示輸入 please input your name:'pythoner' >>> name #執行後name變數有值 "'pythoner'"
有返回值的字串形式的程式碼用eval,沒有返回值的字串形式的程式碼用exec,一般不用compile。
1.2.2 輸入輸出相關 input,print
input:函式接受一個標準輸入資料,返回為 string 型別。
print:列印輸出。
''' 原始碼分析 def print(self, *args, sep=' ', end='\n', file=None): # known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) file: 預設是輸出到螢幕,如果設定為檔案控制代碼,輸出到檔案 sep: 列印多個值之間的分隔符,預設為空格 end: 每一次列印的結尾,預設為換行符 flush: 立即把內容輸出到流檔案,不作快取 """ ''' print(111,222,333,sep='*') # 111*222*333 print(111,end='') print(222) #兩行的結果 111222 f = open('log','w',encoding='utf-8') print('寫入檔案',file=f,flush=True)
1.2.3記憶體相關 hash id
hash:獲取一個物件(可雜湊物件:int,str,Bool,tuple)的雜湊值。
print(hash(12322)) print(hash('123')) print(hash('arg')) print(hash('alex')) print(hash(True)) print(hash(False)) print(hash((1,2,3))) ''' 12322 -2996001552409009098 -4637515981888139739 2311495795356652852 1 0 2528502973977326415 '''
id:用於獲取物件的記憶體地址。
print(id(123)) # 1674055952 print(id('abc')) # 2033192957072
1.2.3檔案操作相關
open:函式用於開啟一個檔案,建立一個 file 物件,相關的方法才可以呼叫它進行讀寫。
1.2.4模組相關__import__
__import__:函式用於動態載入類和函式 。
1.2.5幫助
help:函式用於檢視函式或模組用途的詳細說明。
print(help(list)) Help on class list in module builtins: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(self, value, /) | Return self>value. | | __iadd__(self, value, /) | Implement self+=value. | | __imul__(self, value, /) | Implement self*=value. | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value.n | | __ne__(self, value, /) | Return self!=value. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __repr__(self, /) | Return repr(self). | | __reversed__(...) | L.__reversed__() -- return a reverse iterator over the list | | __rmul__(self, value, /) | Return self*value. | | __setitem__(self, key, value, /) | Set self[key] to value. | | __sizeof__(...) | L.__sizeof__() -- size of L in memory, in bytes | | append(...) | L.append(object) -> None -- append object to end | | clear(...) | L.clear() -> None -- remove all items from L | | copy(...) | L.copy() -> list -- a shallow copy of L | | count(...) | L.count(value) -> integer -- return number of occurrences of value | | extend(...) | L.extend(iterable) -> None -- extend list by appending elements from the iterable | | index(...) | L.index(value, [start, [stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | insert(...) | L.insert(index, object) -- insert object before index | | pop(...) | L.pop([index]) -> item -- remove and return item at index (default last). | Raises IndexError if list is empty or index is out of range. | | remove(...) | L.remove(value) -> None -- remove first occurrence of value. | Raises ValueError if the value is not present. | | reverse(...) | L.reverse() -- reverse *IN PLACE* | | sort(...) | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None None Process finished with exit code 0
1.2.6呼叫相關
callable:函式用於檢查一個物件是否是可呼叫的。如果返回True,object仍然可能呼叫失敗;但如果返回False,呼叫物件ojbect絕對不會成功。
>>>callable(0) False >>> callable("runoob") False >>> def add(a, b): ... return a + b ... >>> callable(add) # 函式返回 True True >>> class A: # 類 ... def method(self): ... return 0 ... >>> callable(A) # 類返回 True True >>> a = A() >>> callable(a) # 沒有實現 __call__, 返回 False False >>> class B: ... def __call__(self): ... return 0 ... >>> callable(B) True >>> b = B() >>> callable(b) # 實現 __call__, 返回 True
1.2.7檢視內建屬性
dir:函式不帶引數時,返回當前範圍內的變數、方法和定義的型別列表;帶引數時,返回引數的屬性、方法列表。如果引數包含方法__dir__(),該方法將被呼叫。如果引數不包含__dir__(),該方法將最大限度地收集引數資訊。
>>>dir() # 獲得當前模組的屬性列表 ['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice'] >>> dir([ ]) # 檢視列表的方法 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__