14,內置函數,和匿名函數
阿新 • • 發佈:2018-05-17
object com raise res 簡單 war copy ret return
作用域相關:
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}
其他類型相關:
eval:執行字符串類型的代碼,並返回最終結果。
print(eval(‘2+2‘)) n = 61 print(eval(‘n + 3‘)) eval(‘print(666)‘)
exec:執行字符串類型的代碼。
s = ‘‘‘ for i in [1,2,3]: print(i) ‘‘‘ exec(s)
compile
‘‘‘ 參數說明: 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。
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(‘ddd‘))#不可哈希,可變類型 print(hash(123))#可哈希,不可變數據類型。 print(hash((1,2)))#可哈希,不可變數據類型。 print(hash(True))#可哈希,不可變數據類型。 print(hash(False))#可哈希,不可變數據類型。
id(用於獲取對象的內存地址)。
a = 123 #可哈希不可變數據類型 b = 123#可哈希不可變數據類型 print(id(a)) print(id(b)) c = ‘123‘#不可哈希,可變數據類型 d = ‘123‘#不可哈希,可變數據類型 print(id(c)) print(id(d))
文件操作相關:
open:函數用於打開一個文件,創建一個file對象,相關的方法才可以調用它進行讀寫。
模塊相關:
import:函數用於動態加載類和函數。
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
14,內置函數,和匿名函數