內(nèi)置函數(shù)就是Python預(yù)先定義的函數(shù),這些內(nèi)置函數(shù)使用方便,無需導(dǎo)入,直接調(diào)用,大大提高使用者的工作效率,也更便于程序的閱讀。截止到Python版本3.9.1,Python一共提供了69個(gè)內(nèi)置函數(shù)。 如果你還沒入門,或剛剛?cè)腴TPython,那么,這篇文章非常適合你。為了方便記憶,木木老師會(huì)將這些內(nèi)置函數(shù)分類介紹給大家。
數(shù)學(xué)運(yùn)算(7個(gè))abs:求數(shù)值的絕對(duì)值 print(abs(-2)) # 絕對(duì)值:2 divmod:返回兩個(gè)數(shù)值的商和余數(shù) print(divmod(20,3)) # 求商和余數(shù):(6,2) max:返回可迭代對(duì)象中的元素中的最大值或者所有參數(shù)的最大值 print(max(7,3,15,9,4,13)) #求最大值:15 min:返回可迭代對(duì)象中的元素中的最小值或者所有參數(shù)的最小值 print(min(5,3,9,12,7,2)) #求最小值:2 pow:返回兩個(gè)數(shù)值的冪運(yùn)算值或其與指定整數(shù)的模值 print(pow(10,2,3)) # 如果給了第三個(gè)參數(shù). 表示最后取余:1 round:對(duì)浮點(diǎn)數(shù)進(jìn)行四舍五入求值 print(round(2.675, 2)) # 五舍六入:2.67 sum:對(duì)元素類型是數(shù)值的可迭代對(duì)象中的每個(gè)元素求和 print(sum([1,2,3,4,5,6,7,8,9,10])) # 求和:55 類型轉(zhuǎn)換(24個(gè))bool:根據(jù)傳入的參數(shù)的邏輯值創(chuàng)建一個(gè)新的布爾值 print(bool(0)) # 數(shù)值0、空序列等值為:False int:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的整數(shù) print(int(3.6)) # 整數(shù):3 float:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的浮點(diǎn)數(shù) print(float (3)) # 浮點(diǎn)數(shù):3.0 complex:根據(jù)傳入?yún)?shù)創(chuàng)建一個(gè)新的復(fù)數(shù) print(complex (1,2)) # 復(fù)數(shù):1+2j str:將數(shù)據(jù)轉(zhuǎn)化為字符串 print(str(123)+'456') #123456 bytearray:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的字節(jié)數(shù)組 ret = bytearray('alex' ,encoding ='utf-8')print(ret[0]) #97print(ret) #bytearray(b'alex')ret[0] = 65 #把65的位置A賦值給ret[0]print(str(ret)) #bytearray(b'Alex') bytes:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的不可變字節(jié)數(shù)組 bs = bytes('今天吃飯了嗎', encoding='utf-8')print(bs) #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97' memoryview:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的內(nèi)存查看對(duì)象 v = memoryview(b'abcefg')print(v[1]) # 98 ord:返回Unicode字符對(duì)應(yīng)的整數(shù) print(ord('中')) # '中'字在編碼表中的位置:20013 chr:返回整數(shù)所對(duì)應(yīng)的Unicode字符 print(chr(65)) # 已知碼位求字符:A bin:將整數(shù)轉(zhuǎn)換成2進(jìn)制字符串 print(bin(10)) # 二進(jìn)制:0b1010 oct:將整數(shù)轉(zhuǎn)化成8進(jìn)制數(shù)字符串 print(oct(10)) # 八進(jìn)制:0o12 hex:將整數(shù)轉(zhuǎn)換成16進(jìn)制字符串 print(hex(10)) # 十六進(jìn)制:0xa tuple:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的元組 print(tuple([1,2,3,4,5,6])) # (1, 2, 3, 4, 5, 6) list:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的列表 print(list((1,2,3,4,5,6))) # [1, 2, 3, 4, 5, 6] dict:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的字典 print(dict(a = 1,b = 2)) # 創(chuàng)建字典: {'b': 2, 'a': 1} range:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的range對(duì)象 for i in range(15,-1,-5):print(i)# 15# 10# 5# 0 set:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的集合 a = set(range(10))print(a) # 創(chuàng)建集合:{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} frozenset:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的不可變集合 a = frozenset(range(10))print(a) #frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) enumerate:根據(jù)可迭代對(duì)象創(chuàng)建枚舉對(duì)象 lst = ['one','two','three','four','five']for index, el in enumerate(lst,1): # 把索引和元素一起獲取,索引默認(rèn)從0開始. 可以更改print(index)print(el)# 1# one# 2# two# 3# three# 4# four# 5# five iter:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的可迭代對(duì)象 lst = [1, 2, 3]for i in iter(lst):print(i)# 1# 2# 3 slice:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的切片對(duì)象 lst = '你好啊'it = reversed(lst) # 不會(huì)改變?cè)斜? 返回一個(gè)迭代器, 設(shè)計(jì)上的一個(gè)規(guī)則print(list(it)) #['啊', '好', '你']lst = [1, 2, 3, 4, 5, 6, 7]print(lst[1:3:1]) #[2,3]s = slice(1, 3, 1) # 切片用的print(lst[s]) #[2,3] super:根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的子類和父類關(guān)系的代理對(duì)象 class A:def add(self, x):y = x+1print(y)class B(A):def add(self, x):super().add(x)b = B()b.add(2) # 3 object:創(chuàng)建一個(gè)新的object對(duì)象 class A:passprint(issubclass(A,object)) #默認(rèn)繼承object類 # Trueprint(dir(object))# ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] 序列操作(8個(gè))all:判斷可迭代對(duì)象的每個(gè)元素是否都為True值 print(all([1,'hello',True,9])) #True any:判斷可迭代對(duì)象的元素是否有為True值的元素 print(any([0,0,0,False,1,'good'])) #True filter:使用指定方法過濾可迭代對(duì)象的元素 def is_odd(n):return n % 2 == 1newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])print(newlist) # [1, 3, 5, 7, 9] map:使用指定方法去作用傳入的每個(gè)可迭代對(duì)象的元素,生成新的可迭代對(duì)象 def f(i):return ilst = [1,2,3,4,5,6,7,]it = map(f, lst) # 把可迭代對(duì)象中的每一個(gè)元素傳遞給前面的函數(shù)進(jìn)行處理. 處理的結(jié)果會(huì)返回成迭代器print(list(it)) #[1, 2, 3, 4, 5, 6, 7] next:返回可迭代對(duì)象中的下一個(gè)元素值 it = iter([1, 2, 3, 4, 5])while True:try:x = next(it)print(x)except StopIteration:break# 1# 2# 3# 4# 5 reversed:反轉(zhuǎn)序列生成新的可迭代對(duì)象 print(list(reversed([1,2,3,4,5]))) # [5, 4, 3, 2, 1] sorted:對(duì)可迭代對(duì)象進(jìn)行排序,返回一個(gè)新的列表 a = [5,3,4,2,1]print(sorted(a,reverse=True)) # [5, 4, 3, 2, 1] zip:聚合傳入的每個(gè)迭代器中相同位置的元素,返回一個(gè)新的元組類型迭代器 my_list = [11,12,13]my_tuple = (21,22,23)print(list(zip(my_list,my_tuple))) # [(11, 21), (12, 22), (13, 23)] 對(duì)象操作(9個(gè))help:返回對(duì)象的幫助信息 print(help(str)) #查看字符串的用途 dir:返回對(duì)象或者當(dāng)前作用域內(nèi)的屬性列表 print(dir(tuple)) #查看元組的方法 id:返回對(duì)象的唯一標(biāo)識(shí)符 s = 'alex'print(id(s)) # 139783780730608 hash:獲取對(duì)象的哈希值 s = 'alex'print(hash(s)) #-168324845050430382lst = [1, 2, 3, 4, 5]print(hash(lst)) #報(bào)錯(cuò),列表是不可哈希的 type:返回對(duì)象的類型,或者根據(jù)傳入的參數(shù)創(chuàng)建一個(gè)新的類型 dict = {'Name': 'Zara', 'Age': 7}print('Variable Type : %s' % type (dict)) # Variable Type : <type 'dict'> len:返回對(duì)象的長(zhǎng)度 mylist = ['apple', 'orange', 'cherry']x = len(mylist)print(x) # 3 ascii:返回對(duì)象的可打印表字符串表現(xiàn)方式 s = 5print(ascii(s)) # 5format:格式化顯示值s = 'hello world!'print(format(s, '^20')) #居中print(format(s, '<20')) #左對(duì)齊print(format(s, '>20')) #右對(duì)齊# hello world!# hello world!# hello world! vars:返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典,或者返回對(duì)象的屬性列表 class Person:name = 'John'age = 36country = 'norway'x = vars(Person)print(x)# {'__module__': '__main__', 'name': 'Bill', 'age': 63, 'country': 'USA', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None} 反射操作(8個(gè))__import__:動(dòng)態(tài)導(dǎo)入模塊 import osname = input('請(qǐng)輸入你要導(dǎo)入的模塊:')__import__(name) # 可以動(dòng)態(tài)導(dǎo)入模塊 isinstance:判斷對(duì)象是否是類或者類型元組中任意類元素的實(shí)例 arg=123print(isinstance(arg, int)) # 輸出True issubclass:判斷類是否是另外一個(gè)類或者類型元組中任意類元素的子類 class A:passclass B(A):passprint(issubclass(B,A)) # 返回 True hasattr:檢查對(duì)象是否含有屬性 class Coordinate:x = 10y = -5z = 0point1 = Coordinate()print(hasattr(point1, 'x'))print(hasattr(point1, 'y'))print(hasattr(point1, 'z'))print(hasattr(point1, 'no')) # 沒有該屬性# True# True# True# False getattr:獲取對(duì)象的屬性值 class Person():age = 14Tom = Person()print(getattr(Tom,'age')) # 14 setattr:設(shè)置對(duì)象的屬性值 class A():name = '吊車尾'a = A()setattr(a, 'age', 24)print(a.age) # 24 delattr:刪除對(duì)象的屬性 class Person:def __init__(self, name, age):self.name = nameself.age = agetom = Person('Tom', 35)print(dir(tom)) # ['__doc__', '__init__', '__module__', 'age', 'name']delattr(tom, 'age')print(dir(tom)) # ['__doc__', '__init__', '__module__', 'name']s callable:檢測(cè)對(duì)象是否可被調(diào)用 a = 10print(callable(a)) #False 變量a不能被調(diào)用 變量操作(2個(gè))globals:返回當(dāng)前作用域內(nèi)的全局變量和其值組成的字典 x = 'hello'a = 8888888print(globals()) #返回一個(gè)全局變量的字典,包括所有導(dǎo)入的變量x,a# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000000000212C2B0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Pythonproject/111/global.py', '__cached__': None, 'x': 'hello', 'a': 8888888} locals:返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典 print(locals())# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10ab79358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_locals_example.py', '__cached__': None} 交互操作(2個(gè))print:向標(biāo)準(zhǔn)輸出對(duì)象打印輸出 print(1,2,3) # 1 2 3 input:讀取用戶輸入值 a = input('請(qǐng)輸入你的姓名') #輸入:張三print(a) # 張三 文件操作(1個(gè))open:使用指定的模式和編碼打開文件,返回文件讀寫對(duì)象 f = open('file',mode='r',encoding='utf-8')f.read()f.close() 編譯執(zhí)行(5個(gè))compile:將字符串編譯為代碼或者AST對(duì)象,使之能夠通過exec語句來執(zhí)行或者eval進(jìn)行求值 code = 'for i in range(3): print(i)'com = compile(code, '', mode='exec')exec(com)# 0# 1# 2 eval:執(zhí)行動(dòng)態(tài)表達(dá)式求值 code = '5+6+7'com = compile(code, '', mode='eval')print(eval(com)) # 18 exec:執(zhí)行動(dòng)態(tài)語句塊 s = 'for i in range(5): print(i)'a = exec(s)# 0# 1# 2# 3# 4 repr:返回一個(gè)對(duì)象的字符串表現(xiàn)形式(給解釋器) class test:def __init__(self,name,age):self.age = ageself.name = namedef __repr__(self):return 'Class_Test[name='+self.name+',age='+str(self.age)+']'t = test('Zhou',30)print(t) # Class_Test[name=Zhou,age=30] breakpoint:暫停腳本的執(zhí)行,允許在程序的內(nèi)部手動(dòng)瀏覽 裝飾器(3個(gè))property:標(biāo)示屬性的裝飾器 class C:def __init__(self):self._name = ''@propertydef name(self):'''i'm the 'name' property.'''return self._name@name.setterdef name(self,value):if value is None:raise RuntimeError('name can not be None')else:self._name = value classmethod:標(biāo)示方法為類方法的裝飾器 class C:@classmethoddef f(cls,arg1):print(cls)print(arg1) staticmethod:標(biāo)示方法為靜態(tài)方法的裝飾器 class Student(object):def __init__(self,name):self.name = name@staticmethoddef sayHello(lang):print(lang)if lang == 'en':print('Welcome!')else:print('你好!') 收集不易,記得給木木一個(gè)小反饋哦~ PS:由于空格原因,這些代碼直接復(fù)制運(yùn)行不了哦~ |
|