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