內置函數 | ||||
---|---|---|---|---|
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
版權聲明:本文爲博主原創文章,未經博主允許不得轉載 https://blog.csdn.net/laokaikai/article/details/81662806