Python 解釋器 (CPython 3.7)內置有 66 個函數,這些函數在任何時刻都是可用的。此文是為了對這 66 個函數進行簡單的梳理,便于以后可能用到它們時能想到。
1. abs(x)
返回一個數的絕對值。參數x 可以是int 、float 或complex 。如果是complex ,則返回這個復數的大?。#?。
2. all(iterable)
如果iterable 的所有元素“是”True ,才返回True ,否則返回False 。若iterable 為空,也返回True 。等價于:
def all(iterable):
for element in iterable:
if not element:
return False
return True
3. any(iterable)
只要iterable 有一個元素“是”True ,就返回True 。若iterable 為空,返回False 。等價于:
def any(iterable):
for element in iterable:
if element:
return True
return False
4. ascii(object)
像repr() 一樣,但將非 ASCII 字符使用\x , \u 或\U 來轉義。
5. bin(x)
將整數x 轉換為二進制字符串(以“0b”開頭)。如果x 不是一個 Python int 對象,它需要定義一個__index__() 方法來返回一個整數。示例:
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
也可以用format() 和 f-string 來完成:
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
參考 format() 。
6. class bool([x])
返回x 的布爾值。如果x 省略,也返回False 。bool 類是int 類的子類,它僅有兩個示例對象True 和False 。
7. breakpoint(args, **kws)
3.7 版新增。
8. class bytearray([source[, encoding[, errors]]])
返回一個字節(jié)數組。參考bytearray 類和bytes 類。
如果可選的source 參數:
- 是一個字符串,則必須提供一個
encoding 參數,bytearray() 會使用str.encoding() 來將字符串轉換為字節(jié)序列。
- 是一個整數,則字節(jié)數組的大小是這個整數,并且以空字節(jié)初始化。
- 是一個符合
buffer 接口的對象,則字節(jié)數組以這個對象的一個只讀 buffer 來初始化。
- 是一個 iterable,那它的元素必須是
[0, 256] 的整數。字節(jié)數組以它的元素來初始化。
若沒有參數,則返回一個大小為 0 的字節(jié)數組。
9. callable(object)
如果對象是可調用的,則返回True ,否則返回Flase 。注意:即使callable(object) 返回True ,object 也有可能無法調用(為什么?);但如果返回False ,則一定無法調用。
如果一個對象有__call__() 方法,則對象是可調用的。
10. chr(i)
返回一個字符(串),這個字符的 Unicode 碼點為整數i 。比如chr(97) 返回字符串'a' ,chr(8364) 返回'€' 。它是ord() 的逆反。
11. @classmethod
裝飾器:將一個普通方法轉換為類方法。
一個類方法的第一個參數為隱式參數:此類cls ,而非此對象self 。示例:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
可以在類上調用(C.f() )也可以在對象上調用(C().f() )。
Python 類方法不同于 Java 和 C++ 中的靜態(tài)方法。如果想使用靜態(tài)方法,參考本文中的staticmethod() 。
12. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
將 source 編譯為 code 或 AST 對象。Code 對象可以被 exec() 或 eval() 執(zhí)行。source 可以是普通字符串、字節(jié)字符串或一個 AST 對象。參考官方 ast 模塊。
示例:
>>> codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)'
>>> codeObejct = compile(codeInString, 'sumstring', 'exec')
>>> exec(codeObejct)
sum = 11
13. class complex([real[, imag]])
返回一個復數 real + imag*1j ?;蛘邔⒁粋€字符串(第一個參數)或數字轉化為復數。
注意:complex('1+2j') 是正確的,但 complex('1 + 2j') 將拋出 ValueError .
14. delattr(object, name)
刪除一個對象的屬性,delattr(x, 'foobar') 等價于 del x.foobar 。參考setattr()
15. class dict(**kwarg), dict(mapping, **kwarg), dict(iterable, **kwarg)
創(chuàng)建一個字典。
16. dir([object])
沒有參數時,返回當前 local 的符號(標識符)。有參數時,返回object 的有效屬性。
如果object 有__dir__() 方法,則會調用它。示例:
>>> import struct
>>> dir() # show the names in the module namespace # doctest: +SKIP
['__builtins__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module # doctest: +SKIP
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
'__initializing__', '__loader__', '__name__', '__package__',
'_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
注意:dir() 主要在交互式環(huán)境中使用,它的輸出不穩(wěn)定,不應在生產環(huán)境中使用。
17. divmod(a, b)
參數為整數時,返回(a // b, a % b) ;參數為浮點數時,返回(math.floor(a / b), a % b) 。而且0 <= abs(a % b) < abs(b) 。
18. enumerate(iterable, start=0)
返回一個 enumerate 對象。示例:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
等價于:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
19. eval(expression, globals=None, locals=None)
估值表達式。globals 必須是一個字典,而locals 可以是任何 mapping 對象。
如果 globals 和 locals 都省略,則使用當前環(huán)境的符號表。示例:
>>> x = 1
>>> eval('x+1')
2
此函數也能用來執(zhí)行任何 code 對象(比如使用 compile() 創(chuàng)建的 code 對象)。但如果這個 code 對象在編譯時的mode 是 'exec' ,那么eval() 將返回None 。
提示:動態(tài)執(zhí)行語句可以使用exec() 。globals() 和locals() 函數分別返回當前的全局和局部符號表,可以用來傳入eval() 和exec() 。
20. exec(object[, globals[, locals]])
動態(tài)執(zhí)行 Python 代碼。其中 object 必須是字符串或 code 對象。示例:
>>> program = 'a = 5\nb=10\nprint("Sum =", a+b)'
>>> exec(program)
Sum = 15
也可以用于獲取用戶的輸入程序:
program = input('Enter a program:')
exec(program)
想要限制用戶能訪問的對象或函數,可以傳入 globals,示例:
>>> from math import *
>>> exec('print(dir())', {'squareRoot': sqrt, 'pow': pow})
['__builtins__', 'pow', 'squareRoot']
# object can have squareRoot() module
>>> exec('print(squareRoot(9))', {'squareRoot': sqrt, 'pow': pow})
3.0
21. filter(function, iterable)
filter() 基于 function 過濾 iterable 的元素,如果 function(element) 返回 True ,則通過過濾。
filter() 等價于:
# when function is defined
(element for element in iterable if function(element))
# when function is None
(element for element in iterable if element)
itertools.filterflase() 是這個函數的反函數。
22. class float([x])
構建浮點數。對于一個 Python 對象x ,float(x) 會嘗試調用x.__float__() 。示例:
>>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity') # “inf”, “Inf”, “INFINITY” 和 “iNfINity” 都行,不區(qū)分大小寫
-inf
23. format(value[, format_spec])
將 value 轉換為格式化后的表示,由 format_spec 控制。
format_spec 的格式為:
[[fill]align][sign][#][0][width][,][.precision][type]
where, the options are
fill ::= any character
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
數字對齊 align 符號含義:
Type |
Meaning |
< |
左對齊 |
^ |
居中對齊 |
> |
右對齊 |
= |
強制符號(+)(-)到最左邊的位置 |
數字類型 type 符號函數
Type |
Meaning |
d |
十進制整數 |
c |
對應的 Unicode 字符 |
b |
二進制格式 |
o |
八進制格式 |
x |
十六進制格式 |
n |
與d 相同,只是它的數字分隔符因區(qū)域設置而不同 |
e |
科學標識法 (e) |
E |
科學表示法 (E) |
f |
顯示定點數 (默認為 6 位小數) |
F |
與f 相同,只是它將inf 顯示為INF ,nan 顯示為NAN |
g |
通用格式,將數字四舍五入到 p 位有效數字(默認為 6 位) |
G |
與g 相同,只是會顯示E 而不是e |
% |
將數字乘以100并且在后面增加一個% |
示例 1:
# d, f and b are type
# integer
>>> print(format(123, "d"))
123
# float arguments
>>> print(format(123.4567898, "f"))
123.456790
# binary format
>>> print(format(12, "b"))
1100
示例 2:“對齊”和“填充”:
# integer
>>> print(format(1234, "*>+7,d"))
*+1,234
# float number
>>> print(format(123.4567, "^-09.3f"))
0123.4570
上例相當于'{:^-09.3f}'.format(123.4567) 。關于 Python String Format,參看 Python String format()
示例 3:重寫__format__()
# custom __format__() method
class Person:
def __format__(self, format):
if(format == 'age'):
return '23'
return 'None'
print(format(Person(), "age"))
輸出為 23 。
24. class frozenset([iterable])
返回一個 frozenset 對象。
25. getattr(object, name[, default])
getattr(x, 'foobar') 等價于x.foobar 。如果屬性 name 不存在,則會嘗試返回 default,若沒有提供 default 則會引發(fā) AttributeError 。
26. globals()
返回當前全局符號表的字典。這個字典總是當前模塊的符號表(在函數或方法中,會返回函數或方法被定義的模塊的全局符號表,而非調用模塊的全局符號表)。
27. hasattr(object, name)
如果 object 有屬性 name,則返回 True ,否則返回False 。這個函數是由getattr() 實現的(測試是否引發(fā)異常)。
28. hash(object)
返回一個對象的哈希值(如果有的話)。哈希值是整數。
這個函數主要用來快速比較兩個對象。在 set 和 dict 的實現中也用到了,因為 set 和 dict 實際上就是可變大小的哈希表。而 list 不是,因此在 list 中查找元素比在 set 和 dict 中查找要慢很多。參考 StackOverflow
特殊:-1 的哈希值是 -2,因為 CPython 里 -1 用來返回錯誤,所以 -1 的哈希值被改成了 -2。所以hash(-1)==hash(-2) 。參考 StackOverflow。
29. help([object])
顯示幫助。用于交互式環(huán)境中使用。參數可以是字符串或對象。
30. hex(x)
將整數x 轉換為十六進制字符串(以“0x”開頭)。如果x 不是一個 Python int 對象,它需要定義一個__index__() 方法來返回一個整數。示例:
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
也可以用format() 和字符串格式字面量f"xxx" 來完成:
>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')
參看 int() 將十六進制字符串使用16為基數轉換為整數。
31. id(object)
返回對象的 id(一個整數)。
CPython 實現:這是對象在內存中的虛擬地址。
32. input([prompt])
顯示 prompt,獲取用戶輸入字符串,并去除結尾的回車。如果讀到 EOF,則會引發(fā)EOFError 。
如果 引入了readline 模塊,input() 會使用它來提供更多特性,如行編輯和歷史記錄。
33. class int([x]), int(x, base=10)
從一個數字或字符串構建一個整數。如果沒有參數,則返回 0。
實際上能使用的 base 包括:0,2-36。
34. isinstance(object, classinfo)
如果 object 是 classinfo 的實例或子類的示例,則返回 True 。如果 classinfo 是一個元組,那么只要 object 是其中一個 class 的實例或子類的實例,也返回 True 。
33. issubclass(class, classinfo)
基本同上。注意:類是自己的子類。
34. iter(object[, sentinel])
返回一個 iterator 對象。第一個參數的類型取決于是否存在 sentinel。
若沒有 sentinel,object 必須支持迭代協(xié)議(實現 __iter__() )或序列協(xié)議(實現從0開始的__getitem()__ ),否則將會引發(fā)TypeError 。
若有 sentinel,那么 object 必須是可調用的對象。這種情況下,調用這個所返回的迭代器的__next__() 會直接調用這個對象(沒有參數)直到它返回的值等于 sentinel,此時StopIteration 會被引發(fā),其他情況下是直接返回值。
一個很有用的應用是使用iter() 來構建一個“塊讀取器”,例如從一個二進制數據庫中讀取固定 block 大小的數據:
from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), ''):
process_block(block)
35. len(s)
返回對象的長度。對象可以是一個序列(string/bytes/tuple/list/range)或一個合集(dict/set/frozen set)。
36.class list([iterable])
返回一個列表。
37. locals()
參考 globals() 。
38. map(function, iterable, ...)
返回一個 map 對象(迭代器),迭代結果為:將 function 施加于 iterable 的每個元素上所產生的返回值。實例:
def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
輸出為:
<map object at 0x7f722da129e8>
{16, 1, 4, 9}
39. max(iterable, *[, key, default]), max(arg1, arg2, **args*[, key])
返回 iterable 最大的元素或兩個以上參數中最大的。
如果 iterable 是空的,則嘗試返回 default。
如果多個元素最大,則返回第一個遇到的。
40. memoryview(obj)
返回一個 memory view 對象。詳見 Memory View。
41. min(iterable, *[, key, default]), min(arg1, arg2, **args*[, key])
參見 max() 。
42. next(iterator[, default])
調用 iterator 的__next__() 來獲得一個返回值。若 iterator 已經耗盡并且提供了 default,則會返回 default。否則會引發(fā)StopIteration 。
43. class object()
返回一個空白的對象。object 是所有類的基類。
注意:object 沒有__dict__ ,所以不能給object 對象任意增加屬性。
__dict__ 是一個存儲對象可寫屬性的字典。
44. oct(x)
將整數x 轉換為八進制字符串(以“0o”開頭)。如果x 不是一個 Python int 對象,它需要定義一個__index__() 方法來返回一個整數。示例:
>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
也可以用format() 和字符串格式字面量f"xxx" 來完成:
>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')
45. open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
打開一個文件,返回一個 file 對象。如果打不開,將會引發(fā) OSError 。
file 可以是一個字符串,或是一個文件描述符 (file descriptor)。
不同 mode 的含義表:
Character |
Meaning |
r |
讀(默認) |
w |
寫,首先會截斷(覆蓋)之前的文件 |
x |
排斥地(exclusively)創(chuàng)建文件,如果之前存在文件則會失敗 |
a |
寫,在原文件后增添 (append) |
b |
二進制模式 |
t |
文本模式(默認) |
+ |
更新文件(讀寫) |
Python 區(qū)分二進制 I/O 和文本 I/O。二進制 I/O 將內容返回為 bytes 對象,而文本 I/O 將內容返回為 str 對象。
buffering 參數是一個可選整數,用來設置緩沖策略。傳入 0 將緩沖關閉(僅在二進制模式下允許);傳入 1 選擇行緩沖(僅在文本模式下有效);傳入大于 1 的數字用來指定緩沖 trunk 的大小。若不指定 buffering,默認情況為:
- 二進制文件使用固定大小的 trunk 來緩沖,trunk 的大小取決于設備的 block 的大小,在大多數系統(tǒng)上是 4096 或 8192。
- “交互式”文本模式(
isatty() 返回True 的文件)使用行緩沖。其他文本文件使用二進制文件的策略。
encoding 指定文件的編碼方式,只能在文本模式下使用。默認的編碼方式取決于系統(tǒng)(可以通過locale.getpreferredencoding() 查看)。參看codec 模塊來查看支持的編碼方式。
errors 用來指定發(fā)生編解碼錯誤時如何處理,只能在文本模式下使用。參看 codec Error Handlers。
為了簡化和標準化錯誤處理,Python 中的 codecs 通常都會接受一個 errors 參數來指定錯誤處理策略。
newline 控制如何解釋”新行“,僅在文本模式下有效。
讀取文件時:
newline |
含義 |
None (默認) |
Universal newline 模式被啟用:輸入可以是\r 、\n 或\r\n ,并且它們都被翻譯成\n 再被讀取出來。 |
' ' |
Universal newline 模式被啟用:輸入可以是\r 、\n 或\r\n ,但它們被原封不動地讀取。 |
'\r' 、'\n' 或'\r\n' |
僅僅適配一種換行符。 |
寫入文件時:
newline |
含義 |
None (默認) |
任何\n 字符都被翻譯為系統(tǒng)默認換行符(os.linesep )。 |
' ' |
寫入\n 。 |
'\r' 、'\n' 或'\r\n' |
寫入對應的換行符。 |
closefd :如果 file 是一個字符串,那么 closefd 只能是 False ,否則將引發(fā)錯誤;如果 file 是一個文件描述符,那么 closefd 可以被設置為 True ,此時這個文件描述符對應的文件即使被關閉了也仍然保持打開。
opener :一個 callable,要被打開的文件會使用 opener(file, flags) 來打開,opener() 需要返回一個打開的文件描述符(比如os.open() )。實例:
>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
... return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
... print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd) # don't leak a file descriptor
46. ord(c)
輸入一個字符,返回這個字符的 Unicode 碼點。例如ord('a') 返回97 。
47. pow(x, y[, z])
返回 x 的 y 次冪(模 z)。
48. print(**objects, sep=' ', end='\n', file=sys.stdout, flush=False*)
所有的非關鍵詞參數都通過str() 被轉換成字符串,以 sep 分隔,以 end 結尾,并將字符串輸出到 file。flush 設為True 能夠強制沖洗緩沖區(qū)。
49. class property(fget=None, fset=None, fdel=None, doc=None)
參考我的這篇文章。
50. range(stop), range(start, stop[, step])
返回一個 range 對象。參考 Sequence Types — list, tuple, range。
51.repr(object)
返回一個代表 object 的字符串。對于許多類型,比如內置類型,repr() 返回的字符串放到eval() 里能直接返回那個對象;對于其他類型,它一般返回一個字符串,兩邊是尖括號,里面包括對象的類型和額外信息(比如名字和內存地址)。一個類可以通過重寫__repr__() 方法來控制repr() 的輸出。
52. reversed(seq)
返回一個逆序的迭代器。seq 必須是一個擁有__reversed__() 方法的對象,或者它支持序列協(xié)議(擁有__len__() 方法和從 0 作為參數開始的__getitem__() 方法)。
53. round(number[, ndigits])
返回 number 在小數點后舍入到 ndigits 精度的結果。如果省略 ndigits,則返回一個舍入后的整數。
注意:舍入方法不是四舍五入,而是靠近最近的偶數。舉例:
>>> round(0.5)
0
>>> round(-0.5)
0
>>> round(1.5)
2
對于一個普通的對象,round() 會嘗試調用對象的__round__() 方法。
round() 對浮點數的行為有時會讓人琢磨不透:round(2.675, 2) 按理說應該返回2.68 ,但實際上它返回2.67 。原因還是 Python 的浮點精度問題。
54. class set([iterable])
返回一個 set 對象。參看 Set Types — set, frozenset。
55. setattr(object, name, value)
和 getattr() 搭配使用。setattr(x, 'foobar', 123) 相當于
x.foobar = 123 。
56. class slice(stop), slice(start, stop[, step])
返回一個 slice 對象,用于對序列切片,代表一個在 range(start, stop, step) 的下標。Python 的擴展下標語法 (在 Python 2.3 引入)也可以生成一個 slice 對象。示例:
>>> class C(object):
... def __getitem__(self, val):
... print val
...
>>> c = C()
>>> c[1:2,3:4]
(slice(1, 2, None), slice(3, 4, None))
>>> c[5:6,7]
(slice(5, 6, None), 7)
57. sorted(iterable, *, key=None, reverse=False)
返回一個排序后的 iterable (升序)。key 是一個 callable,可以用來對復雜對象指定“按什么排序”。
這個函數保證是穩(wěn)定的,即對于“相等”的兩個元素,它們的相對位置不會改變。
58. @staticmethod
將一個方法轉換為靜態(tài)方法。
靜態(tài)方法不接收第一個 implicit 參數(比如 self 和cls )。使用方法為:
class C:
# 使用裝飾器
@staticmethod
def f(arg1, arg2, ...): ...
# 不使用裝飾器
builtin_open = staticmethod(open)
注意它的 classmethod 的區(qū)別:classmethod 可以用來訪問和更改這個類的內部狀態(tài)和屬性,但 staticmethod 不能;staticmethod 的主要作用是把一些和某個類相關的工具函數放到這個類的命名空間下。參看 class method vs static method in Python。
59. class str(object=''), str(object=b'', encoding='utf-8', errors='strict')
返回一個字符串對象。
60. sum(iterable[, start])
將 iterable 的元素求和,再加上 start ,得到總和并返回。start 默認為 0。通常用于整數類型求和。
對于其他類型有更好的求和方法,比如串聯(lián)字符串使用''.join(sequence) 最快;用擴展精度求和浮點數,使用math.fsum() ;將 iterable 串聯(lián)起來可以使用itertools.chain() 。
61. super([type[, object-or-type]])
返回一個代理對象,它能把對方法的調用傳遞給 type 的父類或兄弟類。
一個類的__mro__ 動態(tài)地記錄了“方法解析搜索順序” (Method Resuolution search Order),像是一個繼承鏈,getattr() 和super() 使用__mro__ 來解析對方法的訪問。例如:
>>> class myList(list):
... x = 1
>>> myList.__mro__
(<class '__main__.myList'>, <class 'list'>, <class 'object'>)
super() 主要有兩個用途:
單繼承例子:
class Mammal(object):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
super().__init__('Dog')
d1 = Dog()
由于避免直接使用Mammal.__init__(self, 'Dog') ,有一天改變了Dog 的基類后代碼仍然是可用的。
多重繼承例子:
class Animal:
def __init__(self, animalName):
print(animalName, 'is an animal.');
class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammal):
def __init__(self, NonWingedMammalName):
print(NonWingedMammalName, "can't fly.")
super().__init__(NonWingedMammalName)
class NonMarineMammal(Mammal):
def __init__(self, NonMarineMammalName):
print(NonMarineMammalName, "can't swim.")
super().__init__(NonMarineMammalName)
class Dog(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Dog has 4 legs.');
super().__init__('Dog')
d = Dog()
print('')
bat = NonMarineMammal('Bat')
輸出為:
Dog has 4 legs.
Dog can't swim.
Dog can't fly.
Dog is a warm-blooded animal.
Dog is an animal.
Bat can't swim.
Bat is a warm-blooded animal.
Bat is an animal.
注意到:一行super().__init__('Dog') 實際上把它兩個基類的__init__() 都依次調用了,先調用的是第一個基類,再調用第二個基類。
關于super() 在 Python 多重繼承中的問題,參看 How does Python's super() work with multiple inheritance?
關于 MRO,可以參看 Guido van Rossum 的這一篇文章:Method Resolution Order。
參看 guide to using super()。
62. tuple([iterable])
返回一個 tuple 對象。
63. class type(object), type(name, bases, dict)
返回 object 的類型(object.__class__ )。
通過三個參數,可以動態(tài)構建 class。例如下面兩種寫法等價:
>>> class X:
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
所有“類”的 type 都是 type,包括 type。
64. vars([object])
返回一個對象的__dict__ 屬性。這個對象可以是模塊、類、實例等任何對象。
沒有參數時,vars() 和locals() 等價。
65. zip(**iterables*)
將不同 iterables 里的元素融合,返回一個新的 tuple 的迭代器,第 i 個 tuple 是所有傳入 iterable 里的第 i 個元素。示例:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
zip() 搭配* 使用可以用來解壓:
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
66. __import__(name, globals=None, locals=None, fromlist=(), level=0)
這個函數被import 語句調用。你可以通過重寫這個函數來改變import 語句的行為,只要引入builtins 模塊并對builtins.__import__ 賦值即可。但最好別這么做。你若真想搞點自己的東西,可以看看importlib.import_module() 。
from spam.ham import eggs, sausage as saus 實際上執(zhí)行了
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
(本文完)請選中你要保存的內容,粘貼到此文本框
|