1. 程式人生 > >Python3.6.x中內建函式總結

Python3.6.x中內建函式總結

# -*- coding:utf-8 -*-

"""
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()

"""
from collections import Iterator,Iterable # abs(x) # 求絕對值 print(abs(-1),abs(1)) # all(iterable) # 如果iterable的所有元素都為真,則返回True(iterable為空,返回True) print(all([1,'a',[2]])) # True print(all([0,'a',[]])) # False print(all('')) # True # any(iterable) # 只要iterable中有一個元素為真,則返回True(iterable為空,返回False)
print(any([1,[],''])) # True print(any([0,0.0,'',[],{},set()])) # False print(any([])) # False # ascii(s) # 只在Python3中支援,用於在不支援Unicode的平臺檢視Unicode字串 # 就像repr()那樣,建立物件的可列印形式,但在結果中只是用ascii字元,非ascii字元都轉換為合適的轉義序列。 print(ascii('hello你好')) # 'hello\u4f60\u597d' # repr(obj) # 將其它型別資料轉換為字串,支援大部分內建資料型別
print(repr(123)) # 123 print(repr('hello 你好')) # 'hello 你好' print(repr([1,2,3])) # [1, 2, 3] print(repr({'a':1})) # {'a': 1} print(repr(object())) # <object object at 0x7f4e9de470a0> # str(value='', encoding=None, errors='strict') # 轉換為字串 print(str()) # '' print(str(666)) # 666 print(str(6.66)) # 6.66 print(str(b'666')) # b'666' # bin(x) # 返回一個字串,其中包含整數x的二進位制形式 0b1010 print(bin(0),bin(1),bin(10)) # 0b0 0b1 0b1010 # class bool([x]) # 是class,返回True或False print(bool(),bool(0),bool(1),bool(''),bool('abc'),bool([]),bool([1]),bool(False),bool(True)) # False False True False True False True False True # class bytearray(source=None, encoding=None, errors='strict') # 返回一個位元組陣列,字元範圍[0,255] print(bytearray("hello 你好","utf-8")) # bytearray(b'hello \xe4\xbd\xa0\xe5\xa5\xbd') # bytes(value=b'', encoding=None, errors='strict') # 返回位元組型別,字元範圍[0,255] print(bytes("hello 你好","utf-8")) # b'hello \xe4\xbd\xa0\xe5\xa5\xbd' # callable(o) # 返回True或者False,判斷一個給定物件 o 是否是可呼叫物件 print(callable(1),callable(''),callable(str)) # False False True # chr(x) # 返回Unicode編碼表中整數x對應的字元 print(chr(65),chr(20001)) # A 両 # ord() # 返回單個字元在Unicode碼錶中對應的整數編碼 print(ord('A'),ord('李'),ord('永'),ord('平')) # 65 26446 27704 24179 # @classmethod() # 將一個普通函式轉換為類方法,等價於@classmethond裝飾器 class A(): def func01(*args): print('classmethod()',*args) classmethod(func01) @classmethod def func02(clz,*args): print('@classmethond',*args) A.func01() A.func02() # 輸出 # classmethod() # @classmethond # @staticmethod # 將一個普通函式轉換為靜態方法 class A(): def func01(*args): print('staticmethod()',*args) staticmethod(func01) @staticmethod def func02(*args): print('@staticmethod',*args) A.func01() A.func02() # 輸出 # staticmethod() # @staticmethod # compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) # 將字串格式的原始碼,編譯為可以被exec()或eval()函式執行的程式碼code物件 # source:一個Python模組或多個程式碼塊,或者是單一程式碼塊,或者是一個表示式 # filename:執行時錯誤訊息提示 # mode:與source對應,模組或多個程式碼塊--"exec",單一程式碼塊--"single",表示式--"eval" statements=""" print('-'*50) num=3 while num: print("hello") num-=1 print('-'*50)""" filename="run-time error" codes=compile(source=statements,filename=filename,mode="exec") print(type(codes)) # eval(codes) exec(codes) # 輸出 # <class 'code'> # -------------------------------------------------- # hello # hello # hello # -------------------------------------------------- # eval(expression, globals=None, locals=None) # 執行Python表示式字串或者是經過compile()編譯後生成的code物件 # obj可以是字串物件或者已經由compile編譯過的程式碼物件, # globals和locals是可選的,分別代表了全域性和區域性名稱空間中的物件,其中globals必須是字典,而locals是任意的對映物件 print(eval("2**3")) # 8 print(eval("type({'key':'value'})")) # <class 'dict'> # exec(object[, globals[, locals]]) # 執行Python程式碼字串或者是經過compile()編譯後生成的code物件 statements=""" num=1 if num<3: print("1<3")""" exec(statements) # 1<3 exec('print("exec")') # exec # class complex(real, imag=None) # 返回複數 c=complex(1,2) print(c,c.real,c.imag) c=complex('1+2j') # c=complex('1 +2j') # 報錯ValueError,字串中不能包含空格 # c=complex('1+2i') # 報錯ValueError,複數虛部必須使用英文字母 j 表示 print(c,c.real,c.imag) # 輸出 # (1+2j) 1.0 2.0 # (1+2j) 1.0 2.0 # delattr(obj,attr) # 等價於 del obj.attr # 刪除物件obj的attr屬性 class A: attr_01=1 attr_02=2 print(A.attr_01) delattr(A,'attr_01') # print(A.attr_01) # AttributeError: type object 'A' has no attribute 'attr_01' print(A.attr_02) del A.attr_02 # print(A.attr_02) # AttributeError: type object 'A' has no attribute 'attr_02' # class dict(**kwarg) # class dict(mapping, **kwarg) # class dict(iterable, **kwarg) # 返回一個字典物件 print(dict()) # {} print(dict(a=2,b=1)) # {'b': 1, 'a': 2} print(dict([('a',1),('b',2),('c',3)])) # {'a': 1, 'b': 2, 'c': 3} print(dict({'a':'A','b':'B'})) # {'a': 'A', 'b': 'B'} # dir(obj) # 引數為空,返回當前作用域中的屬性和方法列表 # 引數不為空,返回引數物件obj的作用域中的屬性和方法列表 # 引數不為空,且該引數物件所屬類中過載了 __dir__(self) 運算子,則返回 __dir__(self)的返回值 print(dir()) print(dir(int)) print(dir(dict)) class B(): def __dir__(self): return ['哼','哈'] def func(self): pass b=B() print(dir(b)) # ['哈', '哼'] # divmod(a,b) # 等價於 (a//b,a%b) # 返回長除法的商與餘數組成的元組 print(divmod(10,3),(10//3,10%3)) print(divmod(10,3.0),(10//3.0,10%3.0)) print(divmod(10.0,3),(10.0//3,10.0%3)) # (3, 1) (3, 1) # (3.0, 1.0) (3.0, 1.0) # (3.0, 1.0) (3.0, 1.0) # enumerate(i,start=0) # 根據給定iterable,返回列舉型別物件,是iterator型別 print(list(enumerate('abc',start=1))) for item in enumerate('123',start=0): print(item) # 輸出 # [(1, 'a'), (2, 'b'), (3, 'c')] # (0, 'a') # (1, 'b') # (2, 'c') # filter(function, iterable) # 過濾序列中的值 # filter函式將序列iterable中的每一個元素傳入函式function中,如果返回值為真,則新增到結果集中;否則,過濾掉 # 如果function為None,則將iterable中值為True的元素新增到結果集中 data=[-1,0,1,2,3,False] res=filter(lambda x:x>=0,data) print(res) # <filter object at 0x7f97fe23f7b8> print(list(res)) # [0, 1, 2, 3, False] res=filter(None,data) print(list(res)) # [-1, 1, 2, 3] # class float([x]) # 生成浮點數,x為數字或者字串 # inf:無窮 print(float(),float(1),float('1'),float('+1.23'),float('+1E6'),float('-Infinity'),float(' -12345\n')) # 0.0 1.0 1.0 1.23 1000000.0 -inf -12345.0 # format(value, [format_spec]) # 格式化顯示value的值,型別為str # 如果format_spec為空,則等效於str(value) print(format(123)) # 123 print(format(True)) # True print(format({'a':1,'b':2})) # {'a':1,'b':2} print(format(123,'b')) # 格式化為2進位制 1111011 print(format(123,'o')) # 格式化為8進位制 173 print(format(123,'d')) # 格式化為10進位制 123 print(format(123,'x')) # 格式化為16進位制,使用小寫字母顯示 7b print(format(123,'X')) # 格式化為16進位制,使用大寫在木顯示 7B print(format(123456789.123456789,'e')) # 科學計數法,預設保留6位小數 1.234568e+08 print(format(123456789.123456789,'0.2e')) # 科學計數法,保留2位小數 1.23e+08 print(format(123456789.123456789,'E')) # 科學計數法,1.234568E+08 print(format(123456789.123456789,'0.2E')) # 科學計數法,1.23E+08 print(format(123456789.123456789,'f')) # 小數點計數法,預設保留6位小數,123456789.123457 print(format(123456789.123456789,'0.2f')) # 小數點計數法,保留2位小數,123456789.12 print(format(1.0e+1000,'F'),format(-1.0e+1000,'F')) # 小數點計數法,無窮大轉換為字母 INF,-INF # class set([iterable]) # 獲取一個set例項物件,可變,元素不重複 print(set()) # set() print(set('123')) # {'2', '3', '1'} # class frozenset([iterable]) # 返回一個frozenset例項物件,不可變,元素不重複 print(frozenset()) # frozenset() print(frozenset('123')) # frozenset({'2', '3', '1'}) # getattr(object, name[, default]) # 返回object的name屬性值,name必須是str型別 # 如果不存在name屬性,設定了default返回default值,否則,丟擲異常AttributeError class A(object): attr_01='value_01' print(getattr(A,'attr_01')) print(getattr(A,'attr_02','value_02')) # print(getattr(A,'attr_03')) # AttributeError: type object 'A' has no attribute 'attr_03' # hasattr(object, name) # 判斷object是否擁有屬性name,返回True或False print(hasattr(A,'attr_01')) # True print(hasattr(A,'attr_02')) # False # setattr(object, name, value) # 給object設定屬性name,值為value setattr(A,'attr_02','value_02') print(hasattr(A,'attr_02')) # True # globals() # 返回屬於全域性作用域的屬性或者方法的字典表 print(globals()) # locals() # 返回屬於本地作用域的屬性和方法的字典表 print(locals()) def function(): a,b=1,2 print(locals()) # {'b': 2, 'a': 1} function() # vars(object) # 返回任意物件的__dict__屬性,前提是存在該屬性 print(vars(int)) # hash(object) # 返回object的雜湊值,大小相等的數字,雜湊值一定相同 print(hash(1),hash(1.0)) print(hash(A),hash(A())) print(hash(int),hash(hash)) # help([object]) # 呼叫內建的幫助系統 # object可以為空,module, function, class, method, keyword, or documentation topi # help() # import re # help(re) # help(hash) # help('class') # class int(x=0) # class int(x, base=10) # 將給定資料x從base進位制轉換為10進位制int # x為數字或可轉換為數字的字串,base為數字x本來的進位制 print(int(255)) # 255 print(int('255')) # 255 print(int('255',base=10)) # 255 print(int('255',base=8)) # 173 # oct(x) # 將10進位制數x轉換為8進位制數 print(oct(255)) # 0o377 # hex(x) # 將一個int型別的數字轉換為16進位制 print(hex(255),hex(0)) # 0xff 0x0 # id() # 返回代表object身份的一個int數字,可以認為C語言中"物件的記憶體地址" print(id(0)) print(id(id)) # input([prompt]) # 接收使用者的輸入並返回字串 # value=input('--->') # print(value) # print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) # *args:任意多個字串 # sep:字串之間的分割符,預設為空格 # end:結束符號,預設為換行 \n print('a','b','c',sep='$',end='\n\n') # isinstance(object, classinfo) # 判斷object是否是classinfo的一個例項 class A():pass print(isinstance(1,int)) # True print(isinstance(A(),A)) # True # issubclass(class, classinfo) # 判斷class是否是classinfo的一個子類 class A():pass class B(A):pass print(issubclass(B,A)) # True # iter(object[, sentinel]) # 將一個可迭代物件轉換為迭代器Iterator i=iter('abc') print(type(i)) # next(iterator[, default]) # 返回迭代器的下一個元素 # 如果沒有下一個,返回default引數,如果沒有default,丟擲StopIteration異常 print(next(i),next(i),next(i)) # print(next(i)) # StopIteration print(next(i,'沒有更多元素了')) # len(iterable) # 返回iterable的元素個數 print(len('abc')) # 3 print(len([1,2,3])) # 3 print(len((1,2,3))) # 3 print(len({'a':1})) # 1 print(len({1,2,3})) # 3 # class list([iterable]) # 例項化一個list物件 print(list()) print(list('abcd')) print(list(range(5))) # map(function, iterable, ...) # 在序列中對映函式:map函式會對一個序列物件中的每一個元素應用被傳入的函式,並返回一個包含所有函式呼叫結果的對映集合 # res=map(lambda x:x,[1,2,3]) res=map(lambda x,y:x+y,[1,2,3],[4,5,6]) print(type(res)) print(list(res)) # max() # 返回給定序列中的最大值 print(max(1,2)) # 2 print(max([1,2])) # 2 print(max({'a':2,'b':1})) # b print(max({'a','b'})) # b # min() # 返回給定序列中的最小值 print(min(1,2)) # 1 print(min([1,2])) # 1 print(min({'a':2,'b':1})) # a print(min({'a','b'})) # a # memoryview(object) # 什麼鬼?記憶體檢視?C中的指標? view=memoryview(b'abcd') print(view[0]) # 97 # class object # 返回一個object print(object) #<class 'object'> print(object()) # <object object at 0x7fc4731ef0c0> # open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) # 開啟一個檔案物件 # pow(x,y,[z]) # 2個引數時,等效於x**y # 3個引數時,等效於x**y%z print(pow(10,3)) # 1000 print(pow(10,3,3)) # 1 # class property(fget=None, fset=None, fdel=None, doc=None) # 不懂? # range([start,]stop[,sep]) # 生成數字列表 r=range(5) print(type(r),isinstance(r,Iterator)) # <class 'range'> False for i in range(1,10,2): print(i,end=' ') # 1 3 5 7 9 print('\n') # reversed(seq) # 翻轉序列seq,返回Iterator i=reversed(['a','b','c']) print(i) print(next(i),next(i),next(i),next(i,'沒有了')) # round(number[, ndigits]) # 四捨五入 # ndigits為保留小數點位數,預設為0 print(round(16),round(16.18),round(8.88),round(-8.88)) # 16 16 9 -9 print(round(16,1),round(16.18,1),round(8.88,1),round(-8.88,1)) # 16 16.2 8.9 -8.9 # class slice(stop)¶ # class slice(start, stop[, step]) # 返回一個切片slice物件,表示步距,可用於切片操作,實際上對可迭代物件的切片操作就是呼叫了slice方法 print(slice(5)) # slice(None, 5, None) print(slice(1,5)) # slice(1, 5, None) print(slice(1,5,2)) # slice(1, 5, 2) seq='abcdefghj' print(seq[slice(5)]) # abcde print(seq[slice(1,5,2)])# bd # sorted(iterable, *, key=None, reverse=False) # 對可迭代物件進行排序 # key為函式,依次作用於每個元素 # reverse為是否倒序排序 print(sorted('872Aadbc',key=None,reverse=True)) # ['d', 'c', 'b', 'a', 'A', '8', '7', '2'] print(sorted('872Aadbc',key=lambda x :str.lower(x),reverse=True)) # ['d', 'c', 'b', 'A', 'a', '8', '7', '2'] # sum(iterable[, start]) # 求和:iterable中各元素之和,加上第二個引數start的值 # 第二個引數start預設為0 print(sum([1,2,3])) print(sum([1,2,3],10)) # super([type[, object-or-type]]) # 呼叫父類中的方法 class A(object): def methond(self): print('----A----') class B(A): def methond(self): super(B,self).methond() # 等價於 # super().methond() print('----B----') B.methond(B()) # tuple([iterable]) # 返回一個元祖物件,不可變的list print(tuple(['L','O','V','E','E'])) # type(obj) # 返回obj的資料型別 print(type(0)) print(type('')) print(type([])) print(type((0,))) print(type({})) # zip() # 建立一個迭代器,結果為倆個Iterable中各元素從開始位置開始的對映關係 # 如果2個Iterable中的元素個數不同,則捨棄比較多的元素 ziped=zip('abcd','1234') print(isinstance(ziped,Iterator)) # True print(list(ziped)) # [('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D')] ziped=zip('abc','1234') print(list(ziped)) # [('a', '1'), ('b', '2'), ('c', '3')] ziped=zip('abcd','123') print(list(ziped)) # [('a', '1'), ('b', '2'), ('c', '3')] print(list(zip('abc'))) # [('a',), ('b',), ('c',)] print(list(zip('abc',''))) # [] # __import__(name, globals=None, locals=None, fromlist=(), level=0) # 不常用的高階函式 # import importlib # importlib.import_module('module_name')