Python 官方文檔解讀(1):66 個內置函數

Python 解釋器 (CPython 3.7)內置有 66 個函數,這些函數在任何時刻都是可用的。此文是爲了對這 66 個函數進行簡單的梳理,便於以後可能用到它們時能想到。

1. abs(x)

返回一個數的絕對值。參數x可以是intfloatcomplex。如果是complex,則返回這個複數的大小(模)。

2. all(iterable)

如果iterable的所有元素“是”True,才返回True,否則返回Falseiterable爲空,也返回True等價於:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

3. any(iterable)

只要iterable有一個元素“是”True,就返回Trueiterable爲空,返回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省略,也返回Falsebool類是int類的子類,它僅有兩個示例對象TrueFalse

7. breakpoint(args, **kws)

3.7 版新增。

8. class bytearray([source[, encoding[, errors]]])

返回一個字節數組。參考bytearray類和bytes類。

如果可選的source參數:

  1. 是一個字符串,則必須提供一個encoding參數,bytearray()會使用str.encoding()來將字符串轉換爲字節序列。
  2. 是一個整數,則字節數組的大小是這個整數,並且以空字節初始化。
  3. 是一個符合buffer接口的對象,則字節數組以這個對象的一個只讀 buffer 來初始化。
  4. 是一個 iterable,那它的元素必須是[0, 256] 的整數。字節數組以它的元素來初始化。

若沒有參數,則返回一個大小爲 0 的字節數組。

9. callable(object)

如果對象是可調用的,則返回True,否則返回Flase。注意:即使callable(object)返回Trueobject也有可能無法調用(爲什麼?);但如果返回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++ 中的靜態方法。如果想使用靜態方法,參考本文中的staticmethod()

12. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

source 編譯爲 code 或 AST 對象。Code 對象可以被 exec()eval() 執行。source 可以是普通字符串、字節字符串或一個 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)

創建一個字典。

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()主要在交互式環境中使用,它的輸出不穩定,不應在生產環境中使用。

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 都省略,則使用當前環境的符號表。示例:

>>> x = 1
>>> eval('x+1')
2

此函數也能用來執行任何 code 對象(比如使用 compile()創建的 code 對象)。但如果這個 code 對象在編譯時的mode'exec',那麼eval()將返回None

提示:動態執行語句可以使用exec()globals()locals()函數分別返回當前的全局和局部符號表,可以用來傳入eval()exec()

20. exec(object[, globals[, locals]])

動態執行 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 對象xfloat(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” 都行,不區分大小寫
-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相同,只是它的數字分隔符因區域設置而不同
e 科學標識法 (e)
E 科學表示法 (E)
f 顯示定點數 (默認爲 6 位小數)
F f相同,只是它將inf顯示爲INFnan顯示爲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 則會引發 AttributeError

26. globals()

返回當前全局符號表的字典。這個字典總是當前模塊的符號表(在函數或方法中,會返回函數或方法被定義的模塊的全局符號表,而非調用模塊的全局符號表)。

27. hasattr(object, name)

如果 object 有屬性 name,則返回 True,否則返回False。這個函數是由getattr()實現的(測試是否引發異常)。

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])

顯示幫助。用於交互式環境中使用。參數可以是字符串或對象。

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,則會引發EOFError

如果 引入了readline模塊,input()會使用它來提供更多特性,如行編輯和歷史記錄。

33. class int([x]), int(x, base=10)

從一個數字或字符串構建一個整數。如果沒有參數,則返回 0。

實際上能使用的 base 包括:0,2-36。

34. isinstance(object, classinfo)

如果 objectclassinfo 的實例或子類的示例,則返回 True。如果 classinfo 是一個元組,那麼只要 object 是其中一個 class 的實例或子類的實例,也返回 True

33. issubclass(class, classinfo)

基本同上。注意:類是自己的子類。

34. iter(object[, sentinel])

返回一個 iterator 對象。第一個參數的類型取決於是否存在 sentinel

若沒有 sentinelobject 必須支持迭代協議(實現 __iter__())或序列協議(實現從0開始的__getitem()__),否則將會引發TypeError

若有 sentinel,那麼 object 必須是可調用的對象。這種情況下,調用這個所返回的迭代器的__next__()會直接調用這個對象(沒有參數)直到它返回的值等於 sentinel,此時StopIteration會被引發,其他情況下是直接返回值。

一個很有用的應用是使用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。否則會引發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 對象。如果打不開,將會引發 OSError

file 可以是一個字符串,或是一個文件描述符 (file descriptor)。

不同 mode 的含義表:

Character Meaning
r 讀(默認)
w 寫,首先會截斷(覆蓋)之前的文件
x 排斥地(exclusively)創建文件,如果之前存在文件則會失敗
a 寫,在原文件後增添 (append)
b 二進制模式
t 文本模式(默認)
+ 更新文件(讀寫)

Python 區分二進制 I/O 和文本 I/O。二進制 I/O 將內容返回爲 bytes 對象,而文本 I/O 將內容返回爲 str對象。

buffering 參數是一個可選整數,用來設置緩衝策略。傳入 0 將緩衝關閉(僅在二進制模式下允許);傳入 1 選擇行緩衝(僅在文本模式下有效);傳入大於 1 的數字用來指定緩衝 trunk 的大小。若不指定 buffering,默認情況爲:

  • 二進制文件使用固定大小的 trunk 來緩衝,trunk 的大小取決於設備的 block 的大小,在大多數系統上是 4096 或 8192。
  • “交互式”文本模式(isatty()返回True的文件)使用行緩衝。其他文本文件使用二進制文件的策略。

encoding 指定文件的編碼方式,只能在文本模式下使用。默認的編碼方式取決於系統(可以通過locale.getpreferredencoding()查看)。參看codec模塊來查看支持的編碼方式。

errors 用來指定發生編解碼錯誤時如何處理,只能在文本模式下使用。參看 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字符都被翻譯爲系統默認換行符(os.linesep)。
' ' 寫入\n
'\r''\n''\r\n' 寫入對應的換行符。

closefd :如果 file 是一個字符串,那麼 closefd 只能是 False,否則將引發錯誤;如果 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])

返回 xy 次冪(模 z)。

48. print(**objects, sep=' ', end='\n', file=sys.stdout, flush=False*)

所有的非關鍵詞參數都通過str()被轉換成字符串,以 sep 分隔,以 end 結尾,並將字符串輸出到 fileflush 設爲True能夠強制沖洗緩衝區。

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__()方法的對象,或者它支持序列協議(擁有__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,可以用來對複雜對象指定“按什麼排序”。

這個函數保證是穩定的,即對於“相等”的兩個元素,它們的相對位置不會改變。

58. @staticmethod

將一個方法轉換爲靜態方法。

靜態方法不接收第一個 implicit 參數(比如 selfcls)。使用方法爲:

class C:
    # 使用裝飾器
    @staticmethod
    def f(arg1, arg2, ...): ...
    
    # 不使用裝飾器
    builtin_open = staticmethod(open)

注意它的 classmethod 的區別:classmethod 可以用來訪問和更改這個類的內部狀態和屬性,但 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。通常用於整數類型求和。

對於其他類型有更好的求和方法,比如串聯字符串使用''.join(sequence)最快;用擴展精度求和浮點數,使用math.fsum();將 iterable 串聯起來可以使用itertools.chain()

61. super([type[, object-or-type]])

返回一個代理對象,它能把對方法的調用傳遞給 type 的父類或兄弟類。

一個類的__mro__動態地記錄了“方法解析搜索順序” (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__)。

通過三個參數,可以動態構建 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 實際上執行了

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

(本文完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章