內建函式¶
Python 直譯器有內建多個可隨時使用的函式和型別。以下按照英文字母排序列出。
內建函式 |
|||
|---|---|---|---|
- aiter(async_iterable, /)¶
回傳 非同步疊代器 做為 非同步可疊代物件。相當於呼叫 x.__aiter__()。
注意:與
iter()不同,aiter()沒有兩個引數的變體。在 3.10 版被加入.
- all(iterable, /)¶
如果 iterable 的所有元素皆為真(或 iterable 為空)則回傳
True。等價於:def all(iterable): for element in iterable: if not element: return False return True
- awaitable anext(async_iterator, /)¶
- awaitable anext(async_iterator, default, /)
當進入 await 時,從給定的 asynchronous iterator 中回傳下一個項目(item),疊代完畢則回傳 default 。
這是內建函式
next()的非同步版本,其行為類似於:呼叫 async_iterator 的
__anext__()方法,回傳 awaitable。等待回傳疊代器的下一個值。如果指定 default,當疊代器結束時會回傳該值,否則會引發StopAsyncIteration。在 3.10 版被加入.
- any(iterable, /)¶
如果 iterable 的任一元素為真,回傳
True。如果 iterable 是空的,則回傳False。等價於:def any(iterable): for element in iterable: if element: return True return False
- ascii(object, /)¶
就像函式
repr(),回傳一個表示物件的字串,但是repr()回傳的字串中非 ASCII 編碼的字元會被跳脫 (escape),像是\x、\u和\U。這個函式生成的字串和 Python 2 的repr()回傳的結果相似。
- bin(integer, /)¶
將一個整數轉變為一個前綴為 "0b" 的二進位制字串。結果是一個有效的 Python 運算式。如果 integer 不是 Python 的
int物件,那它需要定義__index__()method 回傳一個整數。舉例來說:>>> bin(3) '0b11' >>> bin(-10) '-0b1010'
如果不一定需要 "0b" 前綴,還可以使用如下的方法。
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110')
See also
enum.bin()to represent negative values as twos-complement.可參考
format()取得更多資訊。
- class bool(object=False, /)¶
回傳一個布林值,即
True或者False。引數會使用標準的真值測試程序來轉換。如果引數為假或者被省略,則回傳False;其他情況回傳True。boolclass(類別)是int的 subclass(子類別)(參見 數值型別 --- int、float、complex),其他 class 不能繼承自它。它只有False和True兩個實例(參見 Boolean 型別 - bool)。在 3.7 版的變更: 現在為僅限位置參數。
- breakpoint(*args, **kws)¶
這個函式將呼叫
sys.breakpointhook()函式,並將args和kws傳遞給它。這將有效地讓你在特定的呼叫點進入除錯器。預設情況下,sys.breakpointhook()呼叫pdb.set_trace()不須帶任何引數。這樣的設計是為了方便使用者,讓他們不需要額外地導入pdb模組或輸入太多程式就可以進入除錯器。然而,可以將sys.breakpointhook()設置為其他函式,並且breakpoint()將自動呼叫該函式,讓你進入所選擇的除錯器。如果無法存取sys.breakpointhook()這個函式,則此函式將引發RuntimeError。預設情況下,
breakpoint()的行為可以透過PYTHONBREAKPOINT環境變數來更改。有關使用詳情,請參考sys.breakpointhook()。請注意,如果
sys.breakpointhook()被替換了,則無法保證此功能。引發一個附帶引數
breakpointhook的稽核事件builtins.breakpoint。在 3.7 版被加入.
- class bytearray(source=b'')
- class bytearray(source, encoding, errors='strict')
回傳一個新的 bytes 陣列。
bytearrayclass 是一個可變的整數序列,包含範圍為 0 <= x < 256 的整數。它有可變序列大部分常見的 method(如在 可變序列型別 中所述),同時也有bytes型別大部分的 method,參見 Bytes 和 Bytearray 的操作。選擇性參數 source 可以被用來以不同的方式初始化陣列:
如果是一個 string,你必須提供 encoding 參數(以及選擇性地提供 errors );
bytearray()會使用str.encode()method 來將 string 轉變成 bytes。如果是一個 integer,陣列則會有該數值的長度,並以 null bytes 來當作初始值。
如果是一個符合 buffer 介面的物件,該物件的唯讀 buffer 會被用來初始化 bytes 陣列。
如果是一個 iterable,它的元素必須是範圍為
0 <= x < 256的整數,並且會被用作陣列的初始值。
如果沒有引數,則建立長度為 0 的陣列。
可參考 Binary Sequence Types --- bytes, bytearray, memoryview 和 Bytearray 物件。
- class bytes(source=b'')
- class bytes(source, encoding, errors='strict')
回傳一個新的 "bytes" 物件,會是一個元素是範圍為
0 <= x < 256整數的不可變序列。bytes是bytearray的不可變版本 — 它的同樣具備不改變物件的 method,也有相同的索引和切片操作。因此,建構函式的引數和
bytearray()相同。Bytes 物件還可以用文字建立,參見 String and Bytes literals。
可參考 Binary Sequence Types --- bytes, bytearray, memoryview、Bytes Objects 和 Bytes 和 Bytearray 的操作。
- callable(object, /)¶
如果引數 object 是可呼叫的,回傳
True,否則回傳False。如果回傳True,呼叫仍可能會失敗;但如果回傳False,則呼叫 object 肯定會失敗。注意 class 是可呼叫的(呼叫 class 會回傳一個新的實例);如果實例的 class 有定義__call__()method,則它是可呼叫的。在 3.2 版被加入: 這個函式一開始在 Python 3.0 被移除,但在 Python 3.2 又被重新加入。
- chr(codepoint, /)¶
回傳代表有特定 Unicode 編碼位置字元的字串。例如,
chr(97)回傳字串'a',而chr(8364)回傳字串'€'。這是ord()的逆函式。引數的有效範圍是 0 到 1,114,111(16 進制表示為 0x10FFFF)。如果它超過這個範圍,會引發
ValueError。
- @classmethod¶
把一個 method 封裝成 class method(類別方法)。
一個 class method 把自己的 class 作為第一個引數,就像一個實例 method 把實例自己作為第一個引數。請用以下慣例來宣告 class method:
class C: @classmethod def f(cls, arg1, arg2): ...
@classmethod語法是一個函式 decorator — 參見 函式定義 中關於函式定義的詳細介紹。一個 class method 可以在 class(如
C.f())或實例(如C().f())上呼叫。實例除了它的 class 資訊,其他都會被忽略。如果一個 class method 在 subclass 上呼叫,subclass 會作為第一個引數傳入。Class method 和 C++ 與 Java 的 static method 是有區別的。如果你想瞭解 static method,請看本節的
staticmethod()。關於 class method 的更多資訊,請參考標準型別階層。在 3.9 版的變更: Class methods 現在可以包裝其他描述器,例如
property()在 3.10 版的變更: Class method 現在繼承了 method 屬性(
__module__、__name__、__qualname__、__doc__和__annotations__),並擁有一個新的__wrapped__屬性。自從版本 3.11 後不推薦使用,已從版本 3.13 中移除。: Class methods 不能再包裝其他的描述器,例如
property()。
- compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)¶
將 source 編譯成程式碼或 AST 物件。程式碼物件可以被
exec()或eval()執行。source 可以是一般的字串、bytes 字串、或者 AST 物件。參見astmodule(模組)的說明文件瞭解如何使用 AST 物件。filename 引數必須是程式碼的檔名;如果程式碼不是從檔案中讀取,可以傳入一些可辨識的值(經常會使用
'<string>'來替代)。mode 引數指定了編譯程式碼時必須用的模式。如果 source 是一系列的陳述式,可以是
'exec';如果是單一運算式,可以是'eval';如果是單個互動式陳述式,可以是'single'(在最後一種情況下,如果運算式執行結果不是None則會被印出來)。可選引數 flags 和 dont_inherit 控制啟用哪個編譯器選項以及允許哪個未來功能。如果兩者都不存在(或兩者都為零),則會呼叫與
compile()相同旗標的程式碼來編譯。如果給定 flags 引數而未給定 dont_inherit(或為零)則無論如何都會使用由 flags 引數所指定的編譯器選項和未來陳述式。如果 dont_inherit 是一個非零整數,則使用 flags 引數 -- 周圍程式碼中的旗標(未來功能和編譯器選項)將被忽略。編譯器選項和 future 陳述式使用 bits 來表示,可以一起被位元操作 OR 來表示複數個選項。需要被具體定義特徵的位元域可以透過
__future__module 中_Feature實例中的compiler_flag屬性來獲得。編譯器旗標可以在astmodule 中搜尋有PyCF_前綴的名稱。引數 optimize 用來指定編譯器的最佳化級別;預設值
-1選擇與直譯器的-O選項相同的最佳化級別。其他級別為0(沒有最佳化;__debug__為真值)、1(assert 被刪除,__debug__為假值)或2(說明字串 (docstring) 也被刪除)。如果編譯的原始碼無效,此函式會引發
SyntaxError或ValueError。如果你想解析 Python 程式碼為 AST 運算式,請參閱
ast.parse()。引發一個附帶引數
source、filename的稽核事件compile。此事件也可能由隱式編譯 (implicit compilation) 所引發。備註
在
'single'或'eval'模式編譯多行程式碼時,輸入必須以至少一個換行符結尾。這使codemodule 更容易檢測陳述式的完整性。警告
如果編譯足夠大或者足夠複雜的字串成 AST 物件時,Python 直譯器會因為 Python AST 編譯器的 stack 深度限制而崩潰。
在 3.2 版的變更: 允許使用 Windows 和 Mac 的換行符號。此外,在
'exec'模式不需要以換行符號結尾。增加了 optimize 參數。在 3.5 版的變更: 在之前的版本,source 中包含 null bytes 會引發
TypeError。在 3.8 版被加入:
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT現在可以傳遞旗標以啟用對頂層await、async for和async with的支援。
- class complex(number=0, /)¶
- class complex(string, /)
- class complex(real=0, imag=0)
將單一字串或數字轉換為複數,或從實部和虛部建立複數。
例如:
>>> complex('+1.23') (1.23+0j) >>> complex('-4.5j') -4.5j >>> complex('-1.23+4.5j') (-1.23+4.5j) >>> complex('\t( -1.23+4.5J )\n') (-1.23+4.5j) >>> complex('-Infinity+NaNj') (-inf+nanj) >>> complex(1.23) (1.23+0j) >>> complex(imag=-4.5) -4.5j >>> complex(-1.23, 4.5) (-1.23+4.5j)
如果引數是字串,它必須包含實數部分(格式與
float()相同)或虛數部分(格式相同,但後綴為'j'或'J'),或同時包含實數部分和虛數部分(在這種情況下,虛數部分的符號是必須的)。字串可以選擇以空白和圓括號'('和')'包圍,這些都會被忽略。字串在'+'、'-'、'j'或'J'後綴和十進位數字之間不能包含空白。例如,complex('1+2j')沒有問題,但complex('1 + 2j')會引發ValueError。更精確地說,輸入必須符合以下文法中的complexvalue產生規則,在去除括號和前後空白字元之後:complexvalue:
floatvalue|floatvalue("j" | "J") |floatvaluesignabsfloatvalue("j" | "J")如果引數是一個數字,則建構函式會像
int和float一樣進行數值轉換。對於一個普通的 Python 物件x,complex(x)會委派給x.__complex__()。如果__complex__()未定義,則會回退 (fall back) 到__float__()。如果__float__()未定義,則會再回退到__index__()。如果提供兩個引數或使用關鍵字引數,每個引數可以是任何數值型別(包括複數)。如果兩個引數都是實數,則回傳一個有實數分量 real 和虛數分量 imag 的複數。如果兩個引數都是複數,則回傳一個包含實數分量
real.real-imag.imag和虛數分量real.imag+imag.real的複數。如果其中一個引數是實數,則在上述運算式中只使用其實數分量。See also
complex.from_number()which only accepts a single numeric argument.如果省略所有引數,則回傳
0j。複數型別在 數值型別 --- int、float、complex 中有相關描述。
在 3.6 版的變更: 可以使用底線將程式碼文字中的數字進行分組。
在 3.8 版的變更: 如果
__complex__()和__float__()未定義,則會回退到__index__()。在 3.14 版之後被棄用: Passing a complex number as the real or imag argument is now deprecated; it should only be passed as a single positional argument.
- delattr(object, name, /)¶
這是
setattr()相關的函式。引數是一個物件和一個字串,該字串必須是物件中某個屬性名稱。如果物件允許,該函式將刪除指定的屬性。例如delattr(x, 'foobar')等價於del x.foobar。name 不必是個 Python 識別符 (identifier)(請見setattr())。
- class dict(**kwargs)
- class dict(mapping, /, **kwargs)
- class dict(iterable, /, **kwargs)
建立一個新的 dictionary(字典)。
dict物件是一個 dictionary class。參見dict和 Mapping Types --- dict 來瞭解這個 class。其他容器型別,請參見內建的
list、set和tupleclass,以及collectionsmodule。
- dir()¶
- dir(object, /)
如果沒有引數,則回傳目前區域作用域 (local scope) 中的名稱列表。如果有引數,它會嘗試回傳該物件的有效屬性列表。
如果物件有一個名為
__dir__()的 method,那麼該 method 將被呼叫,並且必須回傳一個屬性列表。這允許實現自訂__getattr__()或__getattribute__()函式的物件能夠自訂dir()來報告它們的屬性。如果物件不提供
__dir__(),這個函式會嘗試從物件已定義的__dict__屬性和型別物件收集資訊。結果列表並不總是完整的,如果物件有自訂__getattr__(),那結果可能不準確。預設的
dir()機制對不同型別的物件有不同行為,它會試圖回傳最相關而非最完整的資訊:如果物件是 module 物件,則列表包含 module 的屬性名稱。
如果物件是型別或 class 物件,則列表包含它們的屬性名稱,並且遞迴查詢其基礎的所有屬性。
否則,包含物件的屬性名稱列表、它的 class 屬性名稱,並且遞迴查詢它的 class 的所有基礎 class 的屬性。
回傳的列表按字母表排序,例如:
>>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['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()主要是為了便於在互動式提示字元時使用,所以它會試圖回傳人們感興趣的名稱集合,而不是試圖保證結果的嚴格性或一致性,它具體的行為也可能在不同版本之間改變。例如,當引數是一個 class 時,metaclass 的屬性不包含在結果列表中。
- divmod(a, b, /)¶
它將兩個(非複數)數字作為引數,並在執行整數除法時回傳一對商和餘數。對於混合運算元型別,適用二進位算術運算子的規則。對於整數,運算結果和
(a // b, a % b)一致。對於浮點數,運算結果是(q, a % b),q 通常是math.floor(a / b)但可能會比 1 小。在任何情況下,q * b + a % b和 a 基本相等,如果a % b非零,則它的符號和 b 一樣,且0 <= abs(a % b) < abs(b)。
- enumerate(iterable, start=0)¶
回傳一個列舉 (enumerate) 物件。iterable 必須是一個序列、iterator 或其他支援疊代的物件。
enumerate()回傳之 iterator 的__next__()method 回傳一個 tuple(元組),裡面包含一個計數值(從 start 開始,預設為 0)和透過疊代 iterable 獲得的值。>>> 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(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1
- eval(source, /, globals=None, locals=None)¶
- 參數:
source (
str| code object) -- 一個 Python 運算式。globals (
dict|None) -- 全域命名空間(預設值:None)。locals (mapping |
None) -- 區域命名空間(預設:None)。
- 回傳:
被求值的運算式之結果。
- 引發:
語法錯誤會報告為例外。
警告
This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities.
source 引數會被視為一條 Python 運算式(技術上而言,是條件列表)來剖析及求值,而 globals 和 locals 對映分別用作全域和區域命名空間。如果 globals dictionary 存在但缺少
__builtins__的鍵值,那 source 被剖析之前,將為該鍵插入對內建builtinsmodule dictionary 的引用。覆寫__builtins__可以用來限制或更改可用的名稱,但這不是一種安全機制:被執行的程式碼仍然可以存取所有內建名稱。如果 locals 對映被省略,那它的預設值是 globals dictionary。如果兩個對映都被省略,則以在eval()被呼叫的環境中的 globals 和 locals 執行原始碼。請注意,eval() 在封閉 (enclosing) 環境中無法存取巢狀作用域 (non-locals),除非呼叫eval()的作用域已經有參照它們(例如透過nonlocal陳述式)。範例:
>>> x = 1 >>> eval('x+1') 2
這個函式也可以用來執行任意程式碼物件(如被
compile()建立的那些)。這種情況下,傳入的引數是程式碼物件而不是字串。如果編譯該物件時的 mode 引數是'exec',那麼eval()回傳值為None。提示:
exec()函式支援動態執行陳述式。globals()和locals()函式分別回傳目前的全域性和局部性 dictionary,它們對於將引數傳遞給eval()或exec()可能會方便許多。如果給定來源是一個字串,那麼其前後的空格和定位字元會被移除。
另外可以參閱
ast.literal_eval(),該函式可以安全執行僅包含文字的運算式字串。引發一個附帶程式碼物件為引數的稽核事件
exec。也可能會引發程式碼編譯事件。在 3.13 版的變更: globals 和 locals 引數現在可以作為關鍵字傳遞。
在 3.13 版的變更: 如
locals()內建物件所述,已調整預設 locals 命名空間的語意。
- exec(source, /, globals=None, locals=None, *, closure=None)¶
警告
This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities.
這個函式支援動態執行 Python 程式碼。source 必須是字串或者程式碼物件。如果是字串,那麼該字串將被剖析為一系列 Python 陳述式並執行(除非發生語法錯誤)。[1] 如果是程式碼物件,它將被直接執行。無論哪種情況,被執行的程式碼都需要和檔案輸入一樣是有效的(可參閱語言參考手冊中關於檔案輸入的章節)。請注意,即使在傳遞給
exec()函式的程式碼的上下文中,nonlocal、yield和return陳述式也不能在函式之外使用。該函式回傳值是None。無論哪種情況,如果省略了選擇性的部分,程式碼將在目前作用域內執行。如果只提供了 globals 引數,就必須是 dictionary 型別(且不能是 dictionary 的子類別),而且會被用作全域和區域變數。如果同時提供了 globals 和 locals,它們分別被用作全域和區域變數。如果提供了 locals,則它可以是任何對映物件。請記住在 module 層級中全域和區域變數是相同的 dictionary。
備註
當
exec得到兩個獨立的物件作為 globals 和 locals,程式碼會被執行,就像它被嵌入在類別定義中一樣。這表示在執行的程式碼中定義的函式和類別將無法存取在頂層指定的變數(因為在類別定義中,「頂層」變數被視為類別變數)。如果 globals dictionary 不包含
__builtins__鍵值,則將為該鍵插入對內建builtinsmodule dictionary 的引用。覆寫__builtins__可以用來限制或更改可用的名稱,但這不是一種安全機制:被執行的程式碼仍然可以存取所有內建名稱。closure 引數會指定一個閉包 (closure) — 它是一個 cellvar(格變數)的 tuple。只有在 object 是一個含有自由(閉包)變數 (free (closure) variables) 的程式碼物件時,它才有效。Tuple 的長度必須與程式碼物件的
co_freevars屬性完全匹配。引發一個附帶程式碼物件為引數的稽核事件
exec。也可能會引發程式碼編譯事件。備註
預設情況下,locals 的行為如下面
locals()函式描述的一樣。如果你想在exec()函式回傳時知道程式碼對 locals 的變動,請明確地傳遞 locals dictionary 。在 3.11 版的變更: 增加了 closure 參數。
在 3.13 版的變更: globals 和 locals 引數現在可以作為關鍵字傳遞。
在 3.13 版的變更: 如
locals()內建物件所述,已調整預設 locals 命名空間的語意。
- filter(function, iterable, /)¶
用 iterable 中函式 function 為 True 的那些元素,構建一個新的 iterator。iterable 可以是一個序列、一個支援疊代的容器、或一個 iterator。如果 function 是
None,則會假設它是一個識別性函式,即 iterable 中所有假值元素會被移除。請注意,
filter(function, iterable)相當於一個生成器運算式,當 function 不是None的時候為(item for item in iterable if function(item));function 是None的時候為(item for item in iterable if item)。請參閱
itertools.filterfalse(),只有 function 為 false 時才選取 iterable 中元素的互補函式。
- class float(number=0.0, /)¶
- class float(string, /)
回傳從數字或字串生成的浮點數。
例如:
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
如果引數是字串,則它必須是包含十進位制數字的字串,字串前面可以有符號,之前也可以有空格。選擇性的符號有
'+'和'-';'+'對建立的值沒有影響。引數也可以是 NaN(非數字)或正負無窮大的字串。確切地說,除去首尾的空格後,輸入必須遵循以下語法中floatvalue的生成規則:sign: "+" | "-" infinity: "Infinity" | "inf" nan: "nan" digit: <a Unicode decimal digit, i.e. characters in Unicode general category Nd> digitpart:
digit(["_"]digit)* number: [digitpart] "."digitpart|digitpart["."] exponent: ("e" | "E") [sign]digitpartfloatnumber:number[exponent] absfloatvalue:floatnumber|infinity|nanfloatvalue: [sign]absfloatvalue字母大小寫不影響,例如,"inf"、"Inf"、"INFINITY"、"iNfINity" 都可以表示正無窮大。
否則,如果引數是整數或浮點數,則回傳具有相同值(在 Python 浮點精度範圍內)的浮點數。如果引數在 Python 浮點精度範圍外,則會引發
OverflowError。對於一般的 Python 物件
x,float(x)會委派給x.__float__()。如果未定義__float__()則會回退到__index__()。See also
float.from_number()which only accepts a numeric argument.如果沒有引數,則回傳
0.0。數值型別 --- int、float、complex 描述了浮點數型別。
在 3.6 版的變更: 可以使用底線將程式碼文字中的數字進行分組。
在 3.7 版的變更: 現在為僅限位置參數。
在 3.8 版的變更: 如果
__float__()未定義,則會回退到__index__()。
- format(value, format_spec='', /)¶
將 value 轉換為 format_spec 控制的 "格式化" 表示。format_spec 的解釋取決於 value 引數的型別,但是大多數內建型別使用標準格式化語法:格式規格 (Format Specification) 迷你語言。
預設的 format_spec 是一個空字串,它通常和呼叫
str(value)的效果相同。呼叫
format(value, format_spec)會轉換成type(value).__format__(value, format_spec),當搜尋 value 的__format__()method 時,會忽略實例中的字典。如果搜尋到object這個 method 但 format_spec 不為空,或是 format_spec 或回傳值不是字串,則會引發TypeError。在 3.4 版的變更: 當 format_spec 不是空字串時,
object().__format__(format_spec)會引發TypeError。
- class frozenset(iterable=(), /)
回傳一個新的
frozenset物件,它包含選擇性引數 iterable 中的元素。frozenset是一個內建的 class。有關此 class 的文件,請參閱frozenset和 Set Types --- set, frozenset。請參閱內建的
set、list、tuple和dictclass,以及collectionsmodule 來了解其它的容器。
- getattr(object, name, /)¶
- getattr(object, name, default, /)
回傳 object 之具名屬性的值。name 必須是字串。如果該字串是物件屬性之一的名稱,則回傳該屬性的值。例如,
getattr(x, 'foobar')等同於x.foobar。如果指定的屬性不存在,且提供了 default 值,則回傳其值,否則引發AttributeError。name 不必是個 Python 識別符 (identifier)(請見setattr())。備註
由於私有名稱改編 (private name mangling) 是發生在編譯期,因此你必須手動改編私有屬性(有兩個前導底線的屬性)的名稱,才能使用
getattr()來取得它。
- globals()¶
回傳代表目前 module 命名空間的 dictionary。對於在函式中的程式碼來說,這在定義函式時設定且不論該函式是在何處呼叫都會保持相同。
- hasattr(object, name, /)¶
該引數是一個物件和一個字串。如果字串是物件屬性之一的名稱,則回傳
True,否則回傳False。(此功能是透過呼叫getattr(object, name)並檢查是否引發AttributeError來實作的。)
- hash(object, /)¶
回傳該物件的雜湊值(如果它有的話)。雜湊值是整數。它們在 dictionary 查詢元素時用來快速比較 dictionary 的鍵。相同大小的數字數值有相同的雜湊值(即使它們型別不同,如 1 和 1.0)。
備註
請注意,如果物件帶有自訂的
__hash__()方法,hash()將根據運行機器的位元長度來截斷回傳值。
- help()¶
- help(request)
啟動內建的幫助系統(此函式主要以互動式使用)。如果沒有引數,直譯器控制台裡會啟動互動式幫助系統。如果引數是一個字串,則會在 module、函式、class、method、關鍵字或說明文件主題中搜尋該字串,並在控制台上列印幫助資訊。如果引數是其他任意物件,則會生成該物件的幫助頁。
請注意,呼叫
help()時,如果斜線 (/) 出現在函式的參數列表中,這表示斜線前面的參數是僅限位置 (positional-only) 參數。有關更多資訊,請參閱常見問答集中的僅限位置參數條目。此函式會被
sitemodule 加入到內建命名空間。
- hex(integer, /)¶
將整數轉換為以 "0x" 為前綴的小寫十六進位制字串。如果 integer 不是 Python
int物件,則必須定義一個__index__()method 並且回傳一個整數。舉例來說:>>> hex(255) '0xff' >>> hex(-42) '-0x2a'
如果要將整數轉換為大寫或小寫的十六進位制字串,並可選擇有無 "0x" 前綴,則可以使用如下方法:
>>> '%#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')
可參考
format()取得更多資訊。另請參閱
int()將十六進位制字串轉換為以 16 為基數的整數。備註
如果要取得浮點數的十六進位制字串形式,請使用
float.hex()method。
- id(object, /)¶
回傳物件的 "識別性" 。該值是一個整數,在此物件的生命週期中保證是唯一且恆定的。兩個生命期不重疊的物件可能具有相同的
id()值。這是該物件在記憶體中的位址。
引發一個附帶引數
id的稽核事件builtins.id。
- input()¶
- input(prompt, /)
如果有提供 prompt 引數,則將其寫入標準輸出,末尾不帶換行符。接下來,該函式從輸入中讀取一行,將其轉換為字串(去除末尾的換行符)並回傳。當讀取到 EOF 時,則引發
EOFError。例如:>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
如果載入了
readlinemodule,input()將使用它來提供複雜的行編輯和歷史記錄功能。引發一個附帶讀取輸入前的引數
prompt的稽核事件builtins.input。引發一個附帶成功讀取結果的稽核事件
builtins.input/result。
- class int(number=0, /)¶
- class int(string, /, base=10)
回傳一個由數字或字串所構成的整數物件,若沒有給引數則回傳
0。例如:
>>> int(123.45) 123 >>> int('123') 123 >>> int(' -12_345\n') -12345 >>> int('FACE', 16) 64206 >>> int('0xface', 0) 64206 >>> int('01110011', base=2) 115
如果引數定義了
__int__(),則int(x)會回傳x.__int__()。如果引數定義了__index__()則回傳x.__index__()。對於浮點數,則會向零的方向無條件捨去。如果引數不是數字或如果有給定 base,則它必須是個字串、
bytes或bytearray實例,表示基數 (radix) base 中的整數。可選地,字串之前可以有+或-(中間沒有空格)、可有個前導的零、也可被空格包圍、或在數字間有單一底線。一個 n 進制的整數字串,包含各個代表 0 到 n-1 的數字,0–9 可以用任何 Unicode 十進制數字表示,10–35 可以用
a到z(或A到Z)表示。預設的 base 是 10。允許的進位制有 0、2–36。2、8、16 進位制的字串可以在程式碼中用0b/0B、0o/0O、0x/0X前綴來表示,如同程式碼中的整數文字。進位制為 0 的字串將以和程式碼整數字面值 (integer literal in code) 類似的方式來直譯,最後由前綴決定的結果會是 2、8、10、16 進制中的一個,所以int('010', 0)是非法的,但int('010')和int('010', 8)是有效的。整數型別定義請參閱數值型別 --- int、float、complex。
在 3.4 版的變更: 如果 base 不是
int的實例,但 base 物件有base.__index__method,則會呼叫該 method 來取得此進位制所需的整數。以前的版本使用base.__int__而不是base.__index__。在 3.6 版的變更: 可以使用底線將程式碼文字中的數字進行分組。
在 3.7 版的變更: 第一個參數為僅限位置參數。
在 3.8 版的變更: 如果未定義
__int__()則會回退到__index__()。在 3.11 版的變更:
int的字串輸入和字串表示法可以被限制,以避免阻斷服務攻擊 (denial of service attack)。在字串 x 轉換為int時已超出限制,或是在int轉換為字串時將會超出限制時,會引發ValueError。請參閱整數字串轉換的長度限制說明文件。在 3.14 版的變更:
int()不再委派給__trunc__()method。
- isinstance(object, classinfo, /)¶
如果 object 引數是 classinfo 引數的實例,或者是(直接、間接或 virtual)subclass 的實例,則回傳
True。如果 object 不是給定型別的物件,函式始終回傳False。如果 classinfo 是包含物件型別的 tuple(或多個遞迴 tuple)或一個包含多種型別的 聯合型別 (Union Type),若 object 是其中的任何一個物件的實例則回傳True。如果 classinfo 既不是型別,也不是型別 tuple 或型別的遞迴 tuple,那麼會引發TypeError異常。若是先前檢查已經成功,TypeError可能不會再因為不合格的型別而被引發。在 3.10 版的變更: classinfo 可以是一個 聯合型別 (Union Type)。
- issubclass(class, classinfo, /)¶
如果 class 是 classinfo 的 subclass(直接、間接或 virtual),則回傳
True。classinfo 可以是 class 物件的 tuple(或遞迴地其他類似 tuple)或是一個 聯合型別 (Union Type),此時若 class 是 classinfo 中任一元素的 subclass 時則回傳True。其他情況,會引發TypeError。在 3.10 版的變更: classinfo 可以是一個 聯合型別 (Union Type)。
- iter(iterable, /)¶
- iter(callable, sentinel, /)
回傳一個 iterator 物件。根據是否存在第二個引數,第一個引數的意義是非常不同的。如果沒有第二個引數,該單一引數必須是支援 iterable 協定(有
__iter__()method)的集合物件,或必須支援序列協定(有__getitem__()方法,且數字引數從0開始)。如果它不支援這些協定,會引發TypeError。如果有第二個引數 sentinel,那麼第一引數必須是可呼叫的物件,這種情況下生成的 iterator,每次疊代呼叫__next__()時會不帶引數地呼叫 callable;如果回傳的結果是 sentinel 則引發StopIteration,否則回傳呼叫結果。另請參閱 疊代器型別。
iter()的第二種形式有一個好用的應用,是能夠建立一個區塊閱讀器 (block-reader)。例如,從二進位資料庫檔案中讀取固定寬度的區塊,直到檔案的結尾:from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block)
- len(object, /)¶
回傳物件的長度(元素個數)。引數可以是序列(如 string、bytes、tuple、list 或 range)或集合(如 dictionary、set 或 frozen set)。
如果物件長度大於
sys.maxsize,像是range(2 ** 100),則len會引發OverflowError。
- class list(iterable=(), /)
除了是函式,
list也是可變序列型別,詳情請參閱 List(串列) 和 Sequence Types --- list, tuple, range。
- locals()¶
回傳代表目前區域符號表的對映物件,變數名稱為鍵,目前綁定的參照為值。
在模組作用域,以及使用
exec()或eval()單一命名空間時,此函式會回傳與globals()相同的命名空間。在類別作用域中,它會回傳將傳遞給元類別 (metaclass) 建構函式的命名空間。
當使用
exec()或eval(),並分別使用本機和全局參數時,它會回傳傳入函式呼叫的本機命名空間。在上述所有情況下,在指定的執行框架中,每次呼叫
locals()都會回傳相同的對映物件。透過locals()回傳的對映物件所做的變更,會以被指派、重新指派或刪除的區域變數的形式顯示,而指派、重新指派或刪除區域變數會立即影響回傳的對映物件的內容。在optimized scope 中(包括函式、產生器和協程),每次呼叫
locals()都會回傳一個新的字典,其中包含函式的區域變數和任何非區域 cell 參照的目前綁定。在這種情況下,透過回傳的字典所做的名稱綁定變更,不會寫回對應的區域變數或非區域 cell 參照,而且指派、重新指派或刪除區域變數和非區域 cell 參照,不會影響先前回傳字典的內容。在函式、產生器或協程中作為綜合運算的一部分呼叫
locals()等同於在包含的作用域中呼叫它,但綜合運算已初始化的疊代變數將被包含在內。在其他作用域中,它的行為就像綜合運算作為巢狀函式運行一樣。呼叫
locals()作為產生器運算式的一部分,等同於在巢狀的產生器函式中呼叫它。在 3.12 版的變更: 如 PEP 709 所述,更新了綜合運算中
locals()的行為。在 3.13 版的變更: 作為 PEP 667 的一部分,現在定義了變更此函式回傳的對映物件的語意。在 optimized scopes 中的行為現在如上所述。除了被定義外,其他作用域中的行為與先前版本保持不變。
- map(function, iterable, /, *iterables, strict=False)¶
產生一個將 function 應用於 iterable 中所有項目並 yield 回傳結果的疊代器。如果傳遞了額外的 iterables 引數,則 function 必須接受相同個數的引數,且 function 會平行地被應用於所有可疊代物件的項目。當有多個可疊代物件時,項目最少的可疊代物件耗盡時疊代器也會結束。如果 strict 為
True且其中一個可疊代物件在其他可疊代物件之前耗盡,則會拋出ValueError。如果函式的輸入已經被編排為引數的元組,請參閱itertools.starmap()。在 3.14 版的變更: 增加了 strict 參數。
- max(iterable, /, *, key=None)¶
- max(iterable, /, *, default, key=None)
- max(arg1, arg2, /, *args, key=None)
回傳 iterable 中最大的元素,或者回傳兩個以上的引數中最大的。
如果只提供了一個位置引數,它必須是個 iterable,iterable 中最大的元素會被回傳。如果提供了兩個或以上的位置引數,則回傳最大的位置引數。
這個函式有兩個選擇性的僅限關鍵字引數。key 引數能指定單一引數所使用的排序函式,如同
list.sort()的使用方式。default 引數是當 iterable 為空時回傳的物件。如果 iterable 為空,並且沒有提供 default,則會引發ValueError。如果有多個最大元素,則此函式將回傳第一個找到的。這和其他穩定排序工具如
sorted(iterable, key=keyfunc, reverse=True)[0]和heapq.nlargest(1, iterable, key=keyfunc)一致。在 3.4 版的變更: 新增 default 僅限關鍵字參數。
在 3.8 版的變更: key 可以為
None。
- class memoryview(object)
回傳由給定的引數所建立之「memory view(記憶體檢視)」物件。有關詳細資訊,請參閱Memory Views。
- min(iterable, /, *, key=None)¶
- min(iterable, /, *, default, key=None)
- min(arg1, arg2, /, *args, key=None)
回傳 iterable 中最小的元素,或者回傳兩個以上的引數中最小的。
如果只提供了一個位置引數,它必須是 iterable,iterable 中最小的元素會被回傳。如果提供了兩個以上的位置引數,則回傳最小的位置引數。
這個函式有兩個選擇性的僅限關鍵字引數。key 引數能指定單一引數所使用的排序函式,如同
list.sort()的使用方式。default 引數是當 iterable 為空時回傳的物件。如果 iterable 為空,並且沒有提供 default,則會引發ValueError。如果有多個最小元素,則此函式將回傳第一個找到的。這和其他穩定排序工具如
sorted(iterable, key=keyfunc)[0]和heapq.nsmallest(1, iterable, key=keyfunc)一致。在 3.4 版的變更: 新增 default 僅限關鍵字參數。
在 3.8 版的變更: key 可以為
None。
- next(iterator, /)¶
- next(iterator, default, /)
透過呼叫 iterator 的
__next__()method 取得下一個元素。如果 iterator 耗盡,則回傳給定的預設值 default,如果沒有預設值則引發StopIteration。
- class object¶
這是所有其他 class 的基礎,它具有所有 Python class 實例的通用 method。當建構函式被呼叫時,它會回傳一個新的沒有特徵 (featureless) 的物件。這個建構函式不接受任何引數。
- oct(integer, /)¶
將一個整數轉變為一個前綴為 "0o" 的八進位制字串。回傳結果是一個有效的 Python 運算式。如果 integer 不是 Python 的
int物件,那它需要定義__index__()method 回傳一個整數。舉例來說:>>> oct(8) '0o10' >>> oct(-56) '-0o70'
如果要將整數轉換為八進位制字串,不論是否具備 "0o" 前綴,都可以使用下面的方法。
>>> '%#o' % 10, '%o' % 10 ('0o12', '12') >>> format(10, '#o'), format(10, 'o') ('0o12', '12') >>> f'{10:#o}', f'{10:o}' ('0o12', '12')
可參考
format()取得更多資訊。
- open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)¶
開啟 file 並回傳對應的檔案物件。如果該檔案不能開啟,則引發
OSError。關於使用此函式的更多方法,請參閱讀寫檔案。file 是一個類路徑物件,是將被開啟之檔案的路徑(絕對路徑或目前工作目錄的相對路徑),或是要被包裝 (wrap) 檔案的整數檔案描述器 (file descriptor)。(如果有給定檔案描述器,它會隨著回傳的 I/O 物件關閉而關閉,除非 closefd 被設為
False。)mode 是一個選擇性字串,用於指定開啟檔案的模式。預設值是
'r',這意味著它以文字模式開啟並讀取。其他常見模式有:寫入'w'(會捨去已經存在的檔案)、唯一性建立'x'、追加寫入'a'(在一些 Unix 系統上,無論目前的檔案指標在什麼位置,所有 寫入都會追加到檔案末尾)。在文字模式,如果沒有指定 encoding,則根據電腦平臺來決定使用的編碼:呼叫locale.getencoding()來取得目前的本地編碼。(要讀取和寫入原始 bytes,請使用二進位制模式且不要指定 encoding。)可用的模式有:字元
意義
'r'讀取(預設)
'w'寫入,會先清除檔案內容
'x'唯一性建立,如果文件已存在則會失敗
'a'寫入,如果檔案存在則在其末端附加內容
'b'二進制模式
't'文字模式(預設)
'+'更新(讀取並寫入)
預設的模式是
'r'(開啟並讀取文字,同'rt')。'w+'和'w+b'模式會開啟並清除檔案。'r+'和'r+b'模式會開啟且保留檔案內容。如總覽中所述,Python 能區分二進制和文字的 I/O。在二進制模式下開啟的檔案(mode 引數中含有
'b')會將其內容以bytes物件回傳,而不進行任何解碼。在文字模式(預設情況,或當 mode 引數中含有't'),檔案的內容會以str回傳,其位元組已經先被解碼,使用的是取決於平台的編碼系統或是給定的 encoding。備註
Python 不會使用底層作業系統對於文字檔案的操作概念;所有的處理都是由 Python 獨自完成的,因此能獨立於不同平台。
buffering 是一個選擇性的整數,用於設定緩衝策略。傳入 0 表示關閉緩衝(僅在二進制模式下被允許),1 表示行緩衝(line buffering,僅在文字模式下可用),而 >1 的整數是指示一個大小固定的區塊緩衝區 (chunk buffer),其位元組的數量。請注意,此類指定緩衝區大小的方式適用於二進制緩衝 I/O,但是
TextIOWrapper(以mode='r+'開啟的檔案)會有另一種緩衝方式。若要在TextIOWrapper中停用緩衝,可考慮使用io.TextIOWrapper.reconfigure()的write_through旗標。若未給定 buffering 引數,則預設的緩衝策略會運作如下:二進位檔案會以固定大小的區塊進行緩衝;緩衝區的大小為
max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE),當裝置區塊大小可用時。在大多數系統上,緩衝區的長度通常為 128 KB。「互動式」文字檔(
isatty()回傳True的檔案)會使用列緩衝。其他文字檔則使用上述的二進制檔案緩衝策略。
encoding 是用於解碼或編碼檔案的編碼系統之名稱。它只應該在文字模式下使用。預設的編碼系統會取決於平台(根據
locale.getencoding()回傳的內容),但 Python 支援的任何 text encoding(文字編碼)都是可以使用的。關於支援的編碼系統清單,請參閱codecsmodule。errors 是一個選擇性的字串,用於指定要如何處理編碼和解碼的錯誤——它不能在二進制模式下使用。有許多不同的標準錯誤處理程式(error handler,在Error Handlers有列出清單),不過任何已註冊到
codecs.register_error()的錯誤處理程式名稱也都是有效的。標準的名稱包括:'strict'如果發生編碼錯誤,則引發ValueError例外。預設值None也有相同的效果。'ignore'忽略錯誤。請注意,忽略編碼錯誤可能導致資料遺失。'replace'會在格式不正確的資料位置插入一個替換標誌(像是'?')。'surrogateescape'會將任何不正確的位元組表示為低位代理碼元 (low surrogate code unit),範圍從 U+DC80 到 U+DCFF。在寫入資料時,這些代理碼元將會被還原回surrogateescape錯誤處理程式當時所處理的那些相同位元組。這對於處理未知編碼方式的檔案會很好用。'xmlcharrefreplace'僅在寫入檔案時可支援。編碼系統不支援的字元會被替換為適當的 XML 字元參考 (character reference)&#nnn;。'backslashreplace'會用 Python 的反斜線跳脫序列 (backslashed escape sequence) 替換格式不正確的資料。'namereplace'(也僅在寫入時支援)會將不支援的字元替換為\N{...}跳脫序列。
newline 會決定如何剖析資料串流 (stream) 中的換行字元。它可以是
None、''、'\n'、'\r'或'\r\n'。它的運作規則如下:從資料串流讀取輸入時,如果 newline 是
None,則會啟用通用換行模式。輸入資料中的行結尾可以是'\n'、'\r'或'\r\n',這些符號會被轉換為'\n'之後再回傳給呼叫方。如果是'',也會啟用通用換行模式,但在回傳給呼叫方時,行尾符號不會被轉換。如果它是任何其他有效的值,則輸入資料的行只會由給定的字串做結尾,且在回傳給呼叫方時,行尾符號不會被轉換。將輸出寫入資料串流時,如果 newline 是
None,則被寫入的任何'\n'字元都會轉換為系統預設的行分隔符號os.linesep。如果 newline 是''或'\n',則不做任何轉換。如果 newline 是任何其他有效的值,則寫入的任何'\n'字元都將轉換為給定的字串。
如果 closefd 是
False,且給定的 file 引數是一個檔案描述器而不是檔名,則當檔案關閉時,底層的檔案描述器會保持開啟狀態。如果有給定一個檔名,則 closefd 必須是True(預設值);否則將引發錯誤。透過以 opener 傳遞一個可呼叫物件,就可以自訂開啟函式。然後透過以引數 (file, flags) 呼叫 opener,就能取得檔案物件的底層檔案描述器。opener 必須回傳一個開啟的檔案描述器(將
os.open作為 opener 傳入,在功能上的結果會相當於傳入None)。新建立的檔案是不可繼承的。
下面的範例使用
os.open()函式回傳值當作 dir_fd 的參數,從給定的目錄中用相對路徑開啟檔案:>>> 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
open()函式回傳的 file object 型別取決於模式。當open()是在文字模式中開啟檔案時('w'、'r'、'wt'、'rt'等),它會回傳io.TextIOBase的一個 subclass(具體來說,就是io.TextIOWrapper)。使用有緩衝的二進制模式開啟檔案時,回傳的 class 則會是io.BufferedIOBase的 subclass。確切的 class 各不相同:在讀取的二進制模式,它會回傳io.BufferedReader;在寫入和附加的二進制模式,它會回傳io.BufferedWriter,而在讀/寫模式,它會回傳io.BufferedRandom。當緩衝被停用時,會回傳原始資料串流io.FileIO,它是io.RawIOBase的一個 subclass。另請參閱檔案操作模組,例如
fileinput、io(定義了open()的 module )、os、os.path、tempfile以及shutil。引發一個附帶引數
path、mode、flags的稽核事件open。mode和flags引數可能會被原始的呼叫所修改或推論 (infer)。在 3.3 版的變更:
新增 opener 參數。
新增
'x'模式。如果檔案已存在但使用了唯一性建立模式 (
'x'),現在會引發FileExistsError。
在 3.4 版的變更:
檔案在此版本開始是不可繼承的。
在 3.5 版的變更:
如果系統呼叫被中斷,但訊號處理程式沒有引發例外,此函式現在會重試系統呼叫,而不是引發
InterruptedError例外(原因詳見 PEP 475)。增加了
'namereplace'錯誤處理程式。
在 3.6 版的變更:
增加對於實作
os.PathLike物件的支援。在 Windows 上,開啟一個控制臺緩衝區可能會回傳
io.RawIOBase的 subclass,而不是io.FileIO。
在 3.11 版的變更:
'U'模式被移除。
- ord(character, /)¶
Return the ordinal value of a character.
如果引數是單字元字串,則回傳該字元的 Unicode 編碼位置。例如
ord('a')回傳整數97、ord('€')(歐元符號)回傳8364。這是chr()的逆函式。If the argument is a
bytesorbytearrayobject of length 1, return its single byte value. For example,ord(b'a')returns the integer97.
- pow(base, exp, mod=None)¶
回傳 base 的 exp 次方;如果 mod 存在,則回傳 base 的 exp 次方對 mod 取餘數(比直接呼叫
pow(base, exp) % mod計算更高效)。兩個引數形式的pow(exp, exp)等價於次方運算子:base**exp。當引數為內建數值型別且運算元型別為混合型別時,會套用二元算術運算子的強制轉型 (coercion) 規則。對於
int運算元,運算結果會(在強制轉型後)與運算元的型別相同,除非第二個引數是負數;在這種情況下,所有的引數都會被轉換為浮點數並得到浮點數的結果。例如,pow(10, 2)會回傳100,但pow(10, -2)會回傳0.01。如果底數 (base) 是型別為int或float的負數且指數 (exponent) 為非整數,則會傳回複數結果。例如pow(-9, 0.5)會回傳一個接近3j的值。然而,如果底數 (base) 是型別為int或float的負數且指數為整數,則會傳回浮點數結果。例如pow(-9, 2.0)會回傳81.0。對於
int運算元 base 和 exp,如果有給定 mod,則 mod 也必須是整數型別,且 mod 必須不為零。如果有給定 mod 且 exp 為負,則 base 必須與 mod 互質。在這種情況下,會回傳pow(inv_base, -exp, mod),其中 inv_base 是 base 對 mod 的模倒數 (inverse modulo)。以下是一個計算
38對97取模倒數的範例:>>> pow(38, -1, mod=97) 23 >>> 23 * 38 % 97 == 1 True
在 3.8 版的變更: 對於
int運算元,現在pow的三引數形式允許第二個引數為負數,也容許模倒數的計算。在 3.8 版的變更: 允許關鍵字引數。在此之前只支援位置引數。
- print(*objects, sep=' ', end='\n', file=None, flush=False)¶
將 objects 列印到文字資料串流 file,用 sep 分隔並以 end 結尾。如果有給定 sep、end、file 和 flush,那麼它們必須是關鍵字引數的形式。
所有的非關鍵字引數都會像是
str()操作一樣地被轉換為字串,並寫入資料串流,彼此以 sep 分隔,並以 end 結尾。sep 和 end 都必須是字串;它們也可以是None,這表示使用預設值。如果沒有給定 objects,print()就只會寫入 end。file 引數必須是一個有
write(string)method 的物件;如果沒有給定或被設為None,則將使用sys.stdout。因為要列印的引數會被轉換為文字字串,所以print()不能用於二進位模式的檔案物件。對於此類物件,請改用file.write(...)。輸出緩衝通常會由 file 決定。但是如果 flush 為 true,則資料串流會被強制清除。
在 3.3 版的變更: 增加了 flush 關鍵字引數。
- class property(fget=None, fset=None, fdel=None, doc=None)¶
回傳 property 屬性。
fget 是一個用於取得屬性值的函式,fset 是一個用於設定屬性值的函式,fdel 是一個用於刪除屬性值的函式,而 doc 會為該屬性建立一個說明字串。
一個典型的用途是定義一個受管理的屬性
x:class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")
如果 c 是 C 的一個實例,則
c.x將會叫用取得器 (getter),c.x = value會呼叫設定器 (setter),而del c.x會叫用刪除器 (deleter)。如果有給定 doc,它將會是 property 屬性的說明字串。否則,property 會複製 fget 的說明字串(如果它存在的話)。這樣一來,就能夠輕鬆地使用
property()作為裝飾器來建立唯讀屬性:class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
@property裝飾器將voltage()方法變成同名唯讀屬性的 "getter",並將 voltage 的說明字串設成 "Get the current voltage"。- @getter¶
- @setter¶
- @deleter¶
一個屬性物件有
getter、setter和deleter方法,這些方法可作為裝飾器使用,建立一個屬性的副本,並將相應的存取函式設定為被裝飾的函式。最好用一個範例來說明:class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x
此程式碼與第一個範例完全相等。請務必賦予附加函式與原始屬性相同的名稱(在此例中為
x)。回傳的屬性物件也有對應於建構函式引數的屬性
fget、fset和fdel。
在 3.5 版的變更: 屬性物件的 docstrings 現在可以寫入。
- __name__¶
持有屬性名稱的屬性。屬性名稱可在 runtime 變更。
在 3.13 版被加入.
- class range(stop, /)
- class range(start, stop, step=1, /)
與其說是函式,
range實際上是一個不可變的序列型別,如 Ranges 和 Sequence Types --- list, tuple, range 所述。
- repr(object, /)¶
回傳一個包含物件可列印表示的字串。對於許多型別,這個函式會嘗試回傳一個字串,當傳遞給
eval()時,這個字串會產生一個具有相同值的物件;否則,這個表示是一個用角括弧括起來的字串,包含物件型別的名稱,以及額外的資訊,通常包括物件的名稱和位址。一個類別可以透過定義__repr__()方法來控制這個函式對其實例的回傳值。如果sys.displayhook()不可存取,這個函式會引發RuntimeError。這個類別有一個自訂的表示,可以被求值:
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person('{self.name}', {self.age})"
- reversed(object, /)¶
Return a reverse iterator. The argument must be an object which has a
__reversed__()method or supports the sequence protocol (the__len__()method and the__getitem__()method with integer arguments starting at0).
- round(number, ndigits=None)¶
回傳小數點後四捨五入到 ndigits 精度的 number。如果省略 ndigits 或為
None,則會回傳最接近其輸入的整數。For the built-in types supporting
round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, bothround(0.5)andround(-0.5)are0, andround(1.5)is2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted orNone. Otherwise, the return value has the same type as number.For a general Python object
number,rounddelegates tonumber.__round__.備註
The behavior of
round()for floats can be surprising: for example,round(2.675, 2)gives2.67instead of the expected2.68. This is not a bug: it's a result of the fact that most decimal fractions can't be represented exactly as a float. See 浮點數運算:問題與限制 for more information.
- class set(iterable=(), /)
Return a new
setobject, optionally with elements taken from iterable.setis a built-in class. Seesetand Set Types --- set, frozenset for documentation about this class.For other containers see the built-in
frozenset,list,tuple, anddictclasses, as well as thecollectionsmodule.
- setattr(object, name, value, /)¶
This is the counterpart of
getattr(). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,setattr(x, 'foobar', 123)is equivalent tox.foobar = 123.name need not be a Python identifier as defined in Names (identifiers and keywords) unless the object chooses to enforce that, for example in a custom
__getattribute__()or via__slots__. An attribute whose name is not an identifier will not be accessible using the dot notation, but is accessible throughgetattr()etc..備註
Since private name mangling happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to set it with
setattr().
- class slice(stop, /)¶
- class slice(start, stop, step=None, /)
Return a slice object representing the set of indices specified by
range(start, stop, step). The start and step arguments default toNone.Slice objects are also generated when slicing syntax is used. For example:
a[start:stop:step]ora[start:stop, i].See
itertools.islice()for an alternate version that returns an iterator.
- sorted(iterable, /, *, key=None, reverse=False)¶
Return a new sorted list from the items in iterable.
有兩個選擇性引數,只能使用關鍵字引數來指定。
key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example,
key=str.lower). The default value isNone(compare the elements directly).reverse is a boolean value. If set to
True, then the list elements are sorted as if each comparison were reversed.Use
functools.cmp_to_key()to convert an old-style cmp function to a key function.The built-in
sorted()function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal --- this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).The sort algorithm uses only
<comparisons between items. While defining an__lt__()method will suffice for sorting, PEP 8 recommends that all six rich comparisons be implemented. This will help avoid bugs when using the same data with other ordering tools such asmax()that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call the reflected__gt__()method.For sorting examples and a brief sorting tutorial, see 排序技法.
- @staticmethod¶
Transform a method into a static method.
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethod def f(arg1, arg2, argN): ...
@staticmethod語法是一個函式 decorator - 參見 函式定義 中的詳細介紹。A static method can be called either on the class (such as
C.f()) or on an instance (such asC().f()). Moreover, the static method descriptor is also callable, so it can be used in the class definition (such asf()).Static methods in Python are similar to those found in Java or C++. Also, see
classmethod()for a variant that is useful for creating alternate class constructors.Like all decorators, it is also possible to call
staticmethodas a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:def regular_function(): ... class C: method = staticmethod(regular_function)
關於 static method 的更多資訊,請參考 標準型別階層。
在 3.10 版的變更: Static method 現在繼承了 method 屬性(
__module__、__name__、__qualname__、__doc__和__annotations__),並擁有一個新的__wrapped__屬性,且為如一般函式的可呼叫物件。
- class str(*, encoding='utf-8', errors='strict')
- class str(object)
- class str(object, encoding, errors='strict')
- class str(object, *, errors)
Return a
strversion of object. Seestr()for details.stris the built-in string class. For general information about strings, see Text Sequence Type --- str.
- sum(iterable, /, start=0)¶
Sums start and the items of an iterable from left to right and returns the total. The iterable's items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to
sum(). The preferred, fast way to concatenate a sequence of strings is by calling''.join(sequence). To add floating-point values with extended precision, seemath.fsum(). To concatenate a series of iterables, consider usingitertools.chain().在 3.8 版的變更: start 參數可被指定為關鍵字引數。
在 3.12 版的變更: Summation of floats switched to an algorithm that gives higher accuracy and better commutativity on most builds.
在 3.14 版的變更: Added specialization for summation of complexes, using same algorithm as for summation of floats.
- class super¶
- class super(type, object_or_type=None, /)
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
The object_or_type determines the method resolution order to be searched. The search starts from the class right after the type.
For example, if
__mro__of object_or_type isD -> B -> C -> A -> objectand the value of type isB, thensuper()searchesC -> A -> object.The
__mro__attribute of the class corresponding to object_or_type lists the method resolution search order used by bothgetattr()andsuper(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.If the second argument is omitted, the super object returned is unbound. If the second argument is an object,
isinstance(obj, type)must be true. If the second argument is a type,issubclass(type2, type)must be true (this is useful for classmethods).When called directly within an ordinary method of a class, both arguments may be omitted ("zero-argument
super()"). In this case, type will be the enclosing class, and obj will be the first argument of the immediately enclosing function (typicallyself). (This means that zero-argumentsuper()will not work as expected within nested functions, including generator expressions, which implicitly create nested functions.)There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.
The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement "diamond diagrams" where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).
For both use cases, a typical superclass call looks like this:
class C(B): def method(self, arg): super().method(arg) # This does the same thing as: # super(C, self).method(arg)
In addition to method lookups,
super()also works for attribute lookups. One possible use case for this is calling descriptors in a parent or sibling class.Note that
super()is implemented as part of the binding process for explicit dotted attribute lookups such assuper().__getitem__(name). It does so by implementing its own__getattribute__()method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly,super()is undefined for implicit lookups using statements or operators such assuper()[name].Also note that, aside from the zero argument form,
super()is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.For practical suggestions on how to design cooperative classes using
super(), see guide to using super().在 3.14 版的變更:
superobjects are nowpickleableandcopyable.
- class tuple(iterable=(), /)
Rather than being a function,
tupleis actually an immutable sequence type, as documented in Tuple(元組) and Sequence Types --- list, tuple, range.
- class type(object, /)¶
- class type(name, bases, dict, /, **kwargs)
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by
object.__class__.The
isinstance()built-in function is recommended for testing the type of an object, because it takes subclasses into account.With three arguments, return a new type object. This is essentially a dynamic form of the
classstatement. The name string is the class name and becomes the__name__attribute. The bases tuple contains the base classes and becomes the__bases__attribute; if empty,object, the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the__dict__attribute. The following two statements create identicaltypeobjects:>>> class X: ... a = 1 ... >>> X = type('X', (), dict(a=1))
另請參閱:
Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually
__init_subclass__()) in the same way that keywords in a class definition (besides metaclass) would.另請參閱 Customizing class creation。
在 3.6 版的變更: Subclasses of
typewhich don't overridetype.__new__may no longer use the one-argument form to get the type of an object.
- vars()¶
- vars(object, /)
Return the
__dict__attribute for a module, class, instance, or any other object with a__dict__attribute.Objects such as modules and instances have an updateable
__dict__attribute; however, other objects may have write restrictions on their__dict__attributes (for example, classes use atypes.MappingProxyTypeto prevent direct dictionary updates).Without an argument,
vars()acts likelocals().A
TypeErrorexception is raised if an object is specified but it doesn't have a__dict__attribute (for example, if its class defines the__slots__attribute).在 3.13 版的變更: The result of calling this function without an argument has been updated as described for the
locals()builtin.
- zip(*iterables, strict=False)¶
Iterate over several iterables in parallel, producing tuples with an item from each one.
例如:
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): ... print(item) ... (1, 'sugar') (2, 'spice') (3, 'everything nice')
More formally:
zip()returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.Another way to think of
zip()is that it turns rows into columns, and columns into rows. This is similar to transposing a matrix.zip()is lazy: The elements won't be processed until the iterable is iterated on, e.g. by aforloop or by wrapping in alist.One thing to consider is that the iterables passed to
zip()could have different lengths; sometimes by design, and sometimes because of a bug in the code that prepared these iterables. Python offers three different approaches to dealing with this issue:預設情況下,
zip()會在最短的可疊代物件用盡時停止。它會忽略較長可疊代物件中的剩餘項目,將結果截斷到最短可疊代物件的長度:>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'])) [(0, 'fee'), (1, 'fi'), (2, 'fo')]
zip()常常用於可疊代物件被假設等長的情況。在這種情況下,建議使用strict=True選項。它的輸出與一般的zip()相同:>>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True)) [('a', 1), ('b', 2), ('c', 3)]
與預設行為不同的是,如果有一個可疊代物件先於其他可疊代物件耗盡,它會引發
ValueError:>>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True): ... print(item) ... (0, 'fee') (1, 'fi') (2, 'fo') Traceback (most recent call last): ... ValueError: zip() argument 2 is longer than argument 1
如果沒有
strict=True引數,任何導致可疊代物件長度不同的 bug 都會被隱藏,可能會在程式的其他部分表現為難以發現的 bug。較短的可疊代物件可以填充常數值,使所有可疊代物件的長度相同。這可以透過
itertools.zip_longest()來完成。
邊界情況:對於單一可疊代引數,
zip()會回傳一個 1-tuple 的疊代器。如果沒有引數,它會回傳一個空的疊代器。秘訣與技巧:
可疊代物件的從左至右求值順序是有保證的。這使得使用
zip(*[iter(s)]*n, strict=True)將資料序列聚類為 n 個長度群組的慣用語成為可能。這會重複相同的疊代器n次,因此每個輸出 tuple 會有n次呼叫疊代器的結果。這樣做的效果是將輸入分割成 n 個長度的區塊。zip()與*運算子結合可以用來解壓縮 (unzip) 一個 list:>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> list(zip(x, y)) [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True
在 3.10 版的變更: 增加了
strict引數。
- __import__(name, globals=None, locals=None, fromlist=(), level=0)¶
備註
這是一個進階的函式,不像
importlib.import_module(),這在日常 Python 程式設計中並不需要。這個函式被
import陳述式所叫用。它可以被取代(透過引入builtins模組並指定給builtins.__import__),以改變import陳述式的語意,但這樣做是強烈不鼓勵的,因為通常使用 import 鉤子(見 PEP 302)來達到相同的目的會比較簡單,而且也不會造成假設使用預設 import 實作的程式碼問題。我們也不鼓勵直接使用__import__(),而應改用importlib.import_module()。這個函式引入 name 模組,可能會使用給定的 globals 和 locals 來決定如何在套件情境中解釋這個名稱。fromlist 給出應該從 name 給出的模組引入的物件或子模組的名稱。標準的實作完全不使用 locals 引數,而只使用 globals 來決定
import陳述式的套件情境。level 指定使用絕對或相對引入。
0(預設)表示只執行絕對引入。level 的正值表示相對於呼叫__import__()的模組目錄要搜尋的父目錄數目(參見 PEP 328 以了解詳情)。當 name 變數的形式是
package.module時,通常會回傳最上層的套件(直到第一個點為止的名稱),而不是 name 所命名的模組。然而,當給予一個非空的 fromlist 引數時,會回傳以 name 命名的模組。例如,陳述式
import spam會產生類似以下程式碼的位元組碼 (bytecode):spam = __import__('spam', globals(), locals(), [], 0)
陳述式
import spam.ham的結果是這樣的呼叫:spam = __import__('spam.ham', globals(), locals(), [], 0)
請注意
__import__()在這裡如何回傳頂層模組(toplevel module),因為這是由import陳述式綁定名稱的物件。另一方面,陳述式
from spam.ham import eggs, sausage as saus結果是:_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage
這裡,
spam.ham模組會從__import__()回傳。從這個物件中,要引入的名稱會被擷取並指定給它們各自的名稱。如果你只想依名稱引入一個模組(可能在套件中),請使用
importlib.import_module()。在 3.3 版的變更: 不再支援 level 的負值(這也將預設值變為 0)。
在 3.9 版的變更: 當使用命令列選項
-E或-I時,環境變數PYTHONCASEOK現在會被忽略。
註腳