python內建函式大全(含使用用例)
內建函式 | ||||
---|---|---|---|---|
abs() |
delattr() |
hash() |
memoryview() |
set() |
all() |
dict() |
help() |
min() |
setattr() |
any() |
dir() |
hex() |
next() |
slice() |
ascii() |
divmod() |
id() |
object() |
sorted() |
bin() |
enumerate() |
input() |
oct() |
staticmethod() |
bool() |
eval() |
int() |
open() |
str() |
breakpoint() |
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() |
abs()
返回數字的絕對值。引數可以是整數或浮點數
all(iterable)
如果集合中所有元素是true或集合為空集合,返回True
any(iterable)
如果集合中有一項元素是true,返回True;空集合為False
#all and any
lst = []
print(lst, '-all():', all(lst)) #True
print(lst, '-any():', any(lst)) #False
lst0 = ['']
print(lst0, '-all():', all(lst0)) #False
print(lst0, '-any():', any(lst0)) #False
lst1 = [None]
print(lst1, '-all():', all(lst1)) #False
print(lst1, '-any():', any(lst1)) #False
lst2 = [0]
print(lst2, '-all():', all(lst2)) #False
print(lst2, '-any():', any(lst2)) #False
lst3 = [1, None, 'a']
print(lst3, '-all():', all(lst3)) #False
print(lst3, '-any():', any(lst3)) #True
lst4 = [1, '0', 'a']
print(lst4, '-all():', all(lst4)) #True
print(lst4, '-any():', any(lst4)) #True
lst5 = [False, '0', 'a']
print(lst5, '-all():', all(lst5)) #False
print(lst5, '-any():', any(lst5)) #True
ascii(object)
ascii() 函式類似 repr() 函式, 返回一個表示物件的字串, 但是對於字串中的非 ASCII 字元則返回通過 repr() 函式使用 \x, \u 或 \U 編碼的字元
bin(x)
將整數轉換為字首為“0b”的二進位制字串。如果引數'x'不是int物件,則必須定義一個__index__()方法返回整數:
#bin()
print(bin(255)) #0b11111111
print(bin(-255)) #-0b11111111
bool(x)
返回一個布林值,即True
或者之一False
。
#bool()
bool(0) #False
bool(1) #True
bool(-1) #True
bool(2) #True
bool(0.0) #False
bool(1.0) #True
bool('') #False
bool('a') #True
bool(None) #False
breakpoint(* args,_** kws _)
版本3.7中的新功能,此函式會將您置於呼叫站點的偵錯程式中。
bytearray([ _source _[,_encoding _[,_errors _] ] ] )
返回一個新的位元組陣列。由於1Byte = 8Bit,所以0<=陣列每一項<256,返回值是一個可變序列。
- 如果source引數是一個字串,您還必須提供編碼(和可選的, 錯誤)引數,呼叫字串的encode()方法將字串轉換成位元組陣列;
- 如果source引數是一個整數,返回該整數長度的被\x00填充的位元組陣列。
- 如果source引數是實現了buffer介面的Object物件,則使用只讀方式將位元組讀取到位元組陣列後返回。
- 如果source引數是可迭代的,則迭代的每一項必須在[0, 255]之間
- 如果沒有引數,則會建立一個大小為0的陣列。
bytes([ _source _[,_encoding _[,_errors _] ] ] )
與bytearray相似,是位元組組成的有序的不可變序列
callable(物件)
判斷物件引數是否可被呼叫(可被呼叫指的是物件能否使用()括號的方法呼叫)
- 如果object引數顯示為可呼叫,則返回True,否則返回False。
- 如果返回true,呼叫仍然可能失敗,
- 如果為False,則呼叫物件將永遠不會成功。
- 類物件都是可被呼叫物件,類的例項物件是否可呼叫物件,取決於類是否定義了call方法。
版本3.2中的新功能:此功能首先在Python 3.0中刪除,然後在Python 3.2中恢復。
# callable()
callable(1) # False
callable(str) # True
class classA:
pass
callable(classA) # True
instanceA = classA()
callable(instanceA) # False
class classB:
def __call__(self):
print('this is __call__ method')
callable(classB) # True
instanceB = classB()
callable(instanceB) # True
chr(_i _)
返回表示Unicode程式碼點為整數i的字元的字串。例如,chr(97)返回字串'a',與ord()函式相反,引數的有效範圍是0到1,114,111(基數為16的0x10FFFF)。
@classmethod
將方法轉換為類方法。
類方法接收類作為隱式的第一個引數,就像例項方法接收例項一樣。要宣告一個類方法,請使用此習語:
compile(source,filename,mode,flags = 0,dontinherit = False,optimize = -1 _)
將源程式碼編譯為程式碼或AST物件。程式碼物件可以由exec()或執行eval()。 source可以是普通字串,位元組字串或AST物件。
class complex([ _real _[,_imag _] ])
返回值為real + imag * 1j的複數或將字串或數字轉換為複數。如果第一個引數是一個字串,它將被解釋為一個複數,並且必須在沒有第二個引數的情況下呼叫該函式。第二個引數永遠不能是字串。每個引數可以是任何數字型別(包括複數)。如果IMAG被省略,預設為零,並且構造用作數字轉換等int和float。如果省略兩個引數,則返回 0j
。
getattr(物件,名稱)、hasattr(物件,名稱)、setattr(物件,名稱,值)、delattr(物件,名稱)
getattr() hasattr() setattr() delattr()是一組對物件屬性操作的內建函式
- getattr():獲取物件的屬性
- hasattr():檢查物件是否有某屬性
- setattr():設定物件的屬性
- delattr():刪除物件的屬性
#getattr() hasattr() setattr() delattr()
class classX:
attr1 = 'classX`s attr1'
def __init__(self, attr2):
self.attr2 = attr2
instanceX = classX('self.attr2=attr2')
#getattr()
getattr(instanceX, 'attr2', 'not found attr2') # 'self.attr2=attr2'
#hasattr()
hasattr(instanceX, 'attr1') # True
#setattr()
getattr(instanceX, 'attr3', 'not found attr3') # 'not found attr3'
setattr(instanceX, 'attr3', 'attr3`s value')
instanceX.attr3 # 'attr3`s value'
getattr(instanceX, 'attr3', 'not found attr3') # 'attr3`s value'
#delattr()
delattr(instanceX, 'attr3')
getattr(instanceX, 'attr3', 'not found attr3') # 'not found attr3'
instanceX.attr3 # AttributeError: 'classX' object has no attribute 'attr3'
dict()
建立一個字典。
#dict()
dict() #{}
dict({'key1':'val1', 'key2':'val2'}) # {'key1': 'val1', 'key2': 'val2'}
dict(key1='val1', key2='val2') # {'key1': 'val1', 'key2': 'val2'}
dict([('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]) # {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
dict([('key1', 'val1'), ('key2', 'val2'), ('key2', 'val3')]) # {'key1': 'val1', 'key2': 'val3'}
dir([ 物件])
- 如果 dir() 沒有引數,則返回當前作用域中的名稱列表;否則,返回給定 object引數 的一個已排序的屬性名稱列表。
- 如果物件提供了 dir() 方法,則它將會被使用;否則,使用預設的 dir() 邏輯,並返回。
- 結果列表按字母順序排序。
- 當引數是類時,元類屬性不在結果列表中。
divmod(a,b)
將兩個數作為引數,並在使用整數除法時返回由商和餘數組成的一對數
>>> divmod(-10, 3)
(-4, 2)
>>> divmod(9, 3)
(3, 0)
>>> divmod(-10, 3)
(-4, 2)
enumerate(iterable,start = 0)
- enumerate是列舉、列舉的意思
- 對於一個可迭代的(iterable)/可遍歷的物件(如列表、字串),enumerate將其組成一個索引序列,利用它可以同時獲得索引和值
- enumerate多用於在for迴圈中得到計數
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> map = {}
>>>
>>> for index, item in enumerate(lst):
... map.__setitem__(index, item)
>>> print(map)
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g'}
eval(表示式,globals = None,locals = None)
將字串string物件轉化為有效的表示式參與求值運算返回計算結果
引數是一個字串和可選的全域性變數和本地變數。 globals如果存在,必須是字典物件。locals如果存在,則可以是任何Map物件。
>>> eval('1+2')
3
>>> nums = eval('range(10)')
>>>
>>> for item in nums:
... print(item)
...
0
1
2
3
4
5
6
7
8
9
exec(object [, globals[, locals]])
exec語句用來執行儲存在字串或檔案中的Python語句
此函式支援Python程式碼的動態執行。object必須是字串或程式碼物件。如果它是一個字串,則將該字串解析為一組Python語句,然後執行該語句(除非發生語法錯誤)。如果是程式碼物件,則只執行它。在所有情況下,執行的程式碼應該作為檔案輸入有效(請參見“參考手冊”中的“檔案輸入”部分)。返回值是None
。
>>> exec("""for i in range(5):
... print("item: %d" % i)""")
item: 0
item: 1
item: 2
item: 3
item: 4
filter(功能,可迭代)
filter函式用於過濾序列
filter()把傳入的函式依次作用於每個元素,然後根據返回值是True還是False決定保留還是丟棄該元素
>>> # filter()
>>> def isOdd(x):
... return x % 2 == 1
>>> list(filter(isOdd, range(10)))
[1, 3, 5, 7, 9]
format(value [, formatspec_])
格式化數值
>>> format(123456) #換成字串
'123456'
>>> format(128, '<20') #左對齊
'128 '
>>> format(128, '<20b') #轉換成二進位制後左對齊
'10000000 '
>>> format(128, 'b>20') #右對齊後填充b
'bbbbbbbbbbbbbbbbb128'
>>> format(128, '>20') #右對齊
' 128'
>>> format(-128, '=20') #拆分負號和數字分別左右對齊
'- 128'
>>> format(128, '^20') #居中對齊
' 128 '
>>> format(1234567, ',') #千位分隔符
'1,234,567'
>>> format(8, 'b') #轉換成二進位制
'1000'
>>> format(99, 'c') #轉換unicode成字元
'c'
>>> format(0b1000, 'd') # 轉換成十進位制
'8'
>>> format(64,'o') #轉換成8進位制
'100'
>>> format(4560,'x') #轉換成16進位制 小寫字母表示
'11d0'
>>> format(4560,'X') #轉換成16進位制 大寫字母表示
'11D0'
>>> format(1314521,'e') #科學計數法,預設保留小數點後6位
'1.314521e+06'
>>> format(1314521,'0.3e') #科學計數法,保留小數點後3位
'1.315e+06'
>>> format(1314521,'0.3E') #科學計數法,保留小數點後3位
'1.315E+06'
>>> format(1314521,'f') #小數點計數法,預設保留小數點後6位
'1314521.000000'
>>> format(1314521,'0.3f')#小數點計數法,保留小數點後3位
'1314521.000'
class frozenset([iterable])
class set([iterable])
class list([iterable])
class tuple([iterable])
class dict([iterable])
- frozenset()返回一個凍結的集合,凍結後集合不能再新增或刪除任何元素
- set()返回可變,無序不重複的集合
>>> #frozenset() set()
...
>>> aset = set('abdfg')
>>> aset.add('h')
>>> print(aset)
{'f', 'a', 'g', 'd', 'b', 'h'}
>>> aset2 = set([1,2,3,4,2,4,5])
>>> print(aset2)
{1, 2, 3, 4, 5}
>>> fset = frozenset('abcef')
>>> print(fset)
frozenset({'f', 'c', 'a', 'e', 'b'})
>>> fset.add('h')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> aset&fset #交集
{'f', 'a', 'b'}
>>> aset|fset #並集
{'f', 'c', 'a', 'e', 'g', 'd', 'b', 'h'}
>>> aset-fset #差集 aset有的,fset沒有的
{'g', 'h', 'd'}
>>> aset^fset #對稱差集, 單獨存在於兩個集合,對方不存在的
{'g', 'c', 'd', 'h', 'e'}
- list()返回可變有序可重複的集合
- tuple()返回不可變的序列
>>> list(range(6))
[0, 1, 2, 3, 4, 5]
>>> list(['a', 'b', 'c'])
['a', 'b', 'c']
>>> list('中國人民')
['中', '國', '人', '民']
>>> list({'key1':'val1', 'key2':'val2'})
['key1', 'key2']
>>> tuple(range(6))
(0, 1, 2, 3, 4, 5)
>>> tuple(['a', 'b', 'c'])
('a', 'b', 'c')
>>> tuple('中國人民')
('中', '國', '人', '民')
>>> tuple({'key1':'val1', 'key2':'val2'})
('key1', 'key2')
- dict()返回一個鍵值對序列(參見dict函式說明)
globals()
locals()
- globals()返回一個全域性變數的字典,包括所有匯入的變數。
- locals()返回一個區域性變數的字典
hash(物件)
返回物件的雜湊值。
>>> hash(range(6))
8834509408445966602
注意
對於具有自定義hash()方法的物件,請注意hash()根據主機的位寬截斷返回值。
help(物件)
呼叫內建幫助系統。(此函式用於互動式使用。)如果未給出引數,則幫助系統將在直譯器控制檯上啟動。如果引數是字串,則查詢字串作為模組,函式,類,方法,關鍵字或文件主題的名稱,並在控制檯上列印幫助頁面。如果引數是任何其他型別的物件,則會生成物件的幫助頁面。
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>> help('print')
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
hex(x)
將整數轉換為帶有字首“0x”的小寫十六進位制字串。如果x不是Python int物件,則必須定義一個__index__()返回整數的方法。
>>> hex(16)
'0x10'
>>> hex(16.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
>>> class classZ:
... def __index__(self):
... return 16
...
>>> instanceZ = classZ()
>>> hex(instanceZ)
'0x10'
注意
要獲取float的十六進位制字串表示形式,請使用該float.hex()方法。
id(物件)
返回代表物件的“身份”的一個整數,在該生命週期內保證該物件是唯一且恆定的。但在不重合的生命週期裡,可能會出現相同的id值。也可以理解為物件的地址
input([ 提示 ])
接收任意輸入,將所有輸入預設為字串處理,並返回字串型別
class int(x = 0)
class int(x, base = 10)
返回由數字或字串x構造的整數物件,如果沒有給出引數,則返回0。如果x定義__int__(),則int(x)返回x.__int__()。如果x定義__trunc__(),則返回x.__trunc__()。對於浮點數,這將截斷為零。
如果X不是數字或如果base給出,則X必須是一個字串。
>>> int()
0
>>> int(3e3)
3000
>>> int('100', 2)
4
>>> int('0x10', 16)
16
isinstance(object, classinfo)
type(object)
>>> isinstance(2, int)
True
>>> type(2) == int
True
>>> isinstance(2.0, float)
True
>>> type(2.0) == float
True
>>> isinstance(True, bool)
True
>>> type(True) == bool
True
>>> isinstance('2', str)
True
>>> type('2') == str
True
>>>
>>> class classY:
... pass
...
>>> class classYY(classY):
... pass
...
>>> instanceY = classY()
>>> instanceYY = classYY()
>>> isinstance(instanceY, classY)
True
>>> type(instanceY) == classY
True
>>> isinstance(instanceYY, classYY)
True
>>> type(instanceYY) == classYY
True
>>> isinstance(instanceYY, classY)
True
>>> type(instanceYY) == classY
False
- isinstance():如果object引數是classinfo 引數的例項,或者是classinfo子類的例項,則返回true ,否則返回false
- type(): 直接返回物件的型別
issubclass(class, classinfo )
如果class是classinfo的子類,則返回true 。
>>> class father:
... pass
...
>>> class child(father):
... pass
...
>>> issubclass(child, father)
True
iter(object [, sentinel ] )
返回一個迭代器物件。
- object -- 支援迭代的集合物件。
- sentinel -- 如果傳遞了第二個引數,則引數 object 必須是一個可呼叫的物件(如,函式),此時,iter 建立了一個迭代器物件,每次呼叫這個迭代器物件的__next__()方法時,都會呼叫 object。
>>> ll = iter(range(10))
>>> next(ll)
0
>>> next(ll)
1
>>> next(ll)
2
len(s)
返回物件的長度(項數)。引數可以是序列(例如字串,位元組,元組,列表或範圍)或集合(例如字典,集合或凍結集合)。
>>> len(range(10))
10
>>> len('abcde')
5
>>> len(bytearray(30))
30
map(function,iterable,……)
返回一個迭代器,它將function應用於iterable每個項,從而產生結果。如果傳遞了其他iterable引數,則 function必須採用那麼多引數,並且並行地應用於所有迭代的項。
>>> def f(x):
... return x * x
...
>>> ll = range(1, 11)
>>> newll = map(f, ll)
>>> print(list(newll))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
max(iterable,*[,key,default])
max(arg1,arg2,_* args _ [, key])
min(iterable,*[,key,default])
min(arg1,arg2,_* args _ [, key])
返回可迭代中的最大/小項或兩個或多個引數中的最大/小項。
>>> nums = range(1, 11)
>>> max(nums)
10
>>> min(nums)
1
memoryview(obj)
返回記憶體檢視物件
next(iterator [,default])
通過呼叫iterator 的__next__()方法,獲取**iterator **的下一項。如果給定default,則在下一項不存在時返回。
>>> nums = iter(range(5))
>>> next(nums, 'is end')
0
>>> next(nums, 'is end')
1
>>> next(nums, 'is end')
2
>>> next(nums, 'is end')
3
>>> next(nums, 'is end')
4
>>> next(nums, 'is end')
'is end'
oct(x)
將整數轉換為字首為“0o”的八進位制字串。如果x不是Python int物件,則必須定義一個__index__()返回整數的方法。
>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
開啟檔案並返回相應的file物件。如果無法開啟檔案,則引發OSError。
-
file———是一個類似路徑的物件
-
mode———是一個可選字串,用於指定開啟檔案的模式,可用模式為:
字元 | 含義 |
---|---|
'r' |
只讀(預設) |
'w' |
開啟寫入,先截斷檔案 |
'x' |
開啟以進行獨佔建立,如果檔案已存在則失敗 |
'a' |
開啟以進行寫入,如果存在則附加到檔案的末尾 |
'b' |
二進位制模式 |
't' |
文字模式(預設) |
'+' |
開啟磁碟檔案進行更新(讀寫) |
ord(c)
返回字元的Unicode碼。
>>> ord('a')
97
pow(x, y [, z ])
返回x^y,如果z存在返回x^y%z
>>> pow(2, 4)
16
>>> pow(2, 4, 5)
1
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
列印輸出
- objects -- 複數,表示可以一次輸出多個物件。輸出多個物件時,需要用** , **分隔。
- sep -- 用來間隔多個物件,預設值是一個空格。
- end -- 用來設定以什麼結尾。預設值是換行符 \n,我們可以換成其他字串。
- file -- 要寫入的檔案物件。
>>> print('abc', 'def', sep=";", end="!!!")
abc;def!!!>>>
class property(fget=None, fset=None, fdel=None, doc=None)
property()函式中的三個函式分別對應的是獲取屬性的方法、設定屬性的方法以及刪除屬性的方法。
>>> class classT:
... def __init__(self, attrValue):
... self.attr = attrValue
... def setAttr(self, attrValue):
... self.attr = attrValue
... def getAttr(self):
... return self.attr
... def delAttr(self):
... del self.attr
... do = property(getAttr, setAttr, delAttr)
...
>>> instanceT = classT(20)
>>> instanceT.do
20
>>> instanceT.do = 40
>>> del instanceT.do
>>> instanceT.do
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in getAttr
AttributeError: 'classT' object has no attribute 'attr'
range(stop)
range(start, stop[, step])
實際上,它不是一個函式,而是一個不可變的序列型別。
- start: 計數開始,包含start;
- stop: 計數結束,不包括 stop;
- step:步長
>>> range(5)
range(0, 5)
>>> range(2, 5)
range(2, 5)
>>> range(1, 10, 2)
range(1, 10, 2)
repr(object)
str(object='')
str(object=b'', encoding='utf-8', errors='strict')
將object引數轉換為各種形式的字串,與str()函式相似
- repr() 轉化為供直譯器讀取的形式
- str()轉化為適於人閱讀的形式
>>> s = 'hello world \'你好,世界\''
>>> repr(s)
'"hello world \'你好,世界\'"'
>>> str(s)
"hello world '你好,世界'"
>>> str(b"hello world '\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'", encoding = "utf8")
"hello world '你好,世界'"
reversed(seq)
反轉一個序列物件,將其元素從後向前顛倒構建成一個新的迭代器後返回,如果引數seq不是序列物件,則必須定義一個__reversed__()方法
>>> nums = range(10)
>>> new_nums = reversed(nums)
>>> print(list(new_nums))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
round(number[, ndigits])
小返回浮點數x的四捨五入值
>>> round(1, 3)
1
>>> round(1.2352, 1)
1.2
>>> round(1.2352, 2)
1.24
>>> round(1.2352, 3)
1.235
class slice(stop)
class slice(start, stop[, step])
返回表示由指定的索引集的切片物件。start和step預設是None。切片物件主要是對序列物件進行切片取元素
>>> nums = list(range(10))
>>> s = slice(2, 7, 2)
>>> nums[s]
[2, 4, 6]
sorted(iterable, *, key=None, reverse=False)
從iterable中的項返回一個新的排序列表。
有兩個可選引數,必須指定為關鍵字引數。
key指定一個引數的函式,用於從每個列表元素中提取比較鍵:key=str.lower
。預設值為None
(直接比較元素)。
reverse是一個布林值。如果設定為True
,則對列表元素進行排序,就好像每個比較都已反轉一樣。
>>> s = [3,2,1,34,23,9]
>>> sorted(s)
[1, 2, 3, 9, 23, 34]
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@staticmethod
將方法轉換為靜態方法(類方法)。
靜態方法不會接收隱式的第一個引數。要宣告靜態方法,請使用此用法:
>>> class classS:
... @staticmethod
... def fun():
... print('this is static method')
...
>>> classS.fun()
this is static method
sum(iterable[, start])
求和計算
>>> nums = list(range(10))
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sum(nums)
45
>>> sum(nums, 5)
50
super([type[, object-or-type]])
super
([ _type _[,_object-or-type _] ] )
返回一個代理物件, 這個物件負責將方法呼叫分配給第一個引數的一個父類或者同輩的類去完成。
第一個引數的mro屬性決定了搜尋的順序, super指的的是 MRO(Method Resolution Order) 中的下一個類, 而不一定是父類!
super()和getattr() 都使用mro屬性來解析搜尋順序, mro實際上是一個只讀的元組.
#super
class Root:
def root_method(self):
print('this is root_method')
def r_a_method(self):
print('this is root r_a_method')
class A(Root):
def a_method(self):
print('this is a_method')
def r_a_method(self):
print('this is a r_a_method')
class B(Root):
def b_method(self):
print('this is b_method')
class C(A, B):
def c_method(self):
super().a_method()
super().r_a_method()
instanceC = C()
instanceC.c_method()
vars([object])
返回物件object的屬性和屬性值的字典物件
>>> class classV:
... a = 1
... def v_m(self):
... return 2
...
>>> vars(classV)
mappingproxy({'__module__': '__main__', 'a': 1, 'v_m': <function classV.v_m at 0x00000000028400D0>, '__dict__': <attribute '__dict__' of 'classV' objects>, '__weakref__': <attribute '__weakref__' of 'classV' objects>, '__doc__': None})
>>> instanceV = classV()
>>> vars(instanceV)
{}
zip(*iterables)
建立一個聚合每個迭代器元素的tuple迭代器。
>>> tuple(zip())
()
>>> l1 = [1,3,5,7,9]
>>> l2 = [2,4,6,8,10]
>>> tuple(zip(l1,l2))
((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
>>> l3 = ['a','b','c','d','e','f']
>>> tuple(zip(l1,l2,l3))
((1, 2, 'a'), (3, 4, 'b'), (5, 6, 'c'), (7, 8, 'd'), (9, 10, 'e'))
__import__(name, globals=None, locals=None, fromlist=(), level=0)
-
函式功能用於動態的匯入模組,主要用於反射或者延遲載入模組。
-
import(module)相當於import module