內建函式¶
Python 直譯器有內建多個可隨時使用的函式和型別。以下按照英文字母排序列出。
內建函式 |
|||
---|---|---|---|
- aiter(async_iterable)¶
回傳 非同步疊代器 做為 非同步可疊代物件。相當於呼叫 x.__aiter__()。
注意:與
iter()
不同,aiter()
沒有兩個引數的變體。Added in version 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
。Added in version 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(x)¶
將一個整數轉變為一個前綴為 "0b" 的二進位制字串。結果是一個有效的 Python 運算式。如果 x 不是 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')
可參考
format()
獲取更多資訊。
- class bool(object=False, /)¶
返回布尔值,即
True
或False
中的一个。 其参数将使用标准的 真值测试过程 来转换。 如果该参数为假值或被省略,则返回False
;在其他情况下,将返回True
。bool
类是int
的子类 (参见 數值型別 --- int、float、complex)。 它不能被继续子类化。 它只有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
。Added in version 3.7.
- class bytearray(source=b'')
- class bytearray(source, encoding)
- class bytearray(source, encoding, errors)
回傳一個新的 bytes 陣列。
bytearray
class 是一個可變的整數序列,包含範圍為 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 的陣列。
可參考 二进制序列类型 --- bytes, bytearray, memoryview 和 bytearray 对象。
- class bytes(source=b'')
- class bytes(source, encoding)
- class bytes(source, encoding, errors)
回傳一個新的 "bytes" 物件,會是一個元素是範圍為
0 <= x < 256
整數的不可變序列。bytes
是bytearray
的不可變版本 — 它的同樣具備不改變物件的 method,也有相同的索引和切片操作。因此,建構函式的引數和
bytearray()
相同。Bytes 物件還可以用文字建立,參見 字符串与字节串字面值。
可參考 二进制序列类型 --- bytes, bytearray, memoryview、bytes 对象 和 bytes 和 bytearray 操作。
- callable(object)¶
如果引數 object 是可呼叫的,回傳
True
,否則回傳False
。如果回傳True
,呼叫仍可能會失敗;但如果回傳False
,則呼叫 object 肯定會失敗。注意 class 是可呼叫的(呼叫 class 會回傳一個新的實例);如果實例的 class 有定義__call__()
method,則它是可呼叫的。Added in version 3.2: 這個函式一開始在 Python 3.0 被移除,但在 Python 3.2 又被重新加入。
- chr(i)¶
回傳代表字元之 Unicode 編碼位置為整數 i 的字串。例如,
chr(97)
回傳字串'a'
,而chr(8364)
回傳字串'€'
。這是ord()
的逆函式。引數的有效範圍是 0 到 1,114,111(16 進制表示為 0x10FFFF)。如果 i 超過這個範圍,會引發
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 物件。參見ast
module(模組)的說明文件瞭解如何使用 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
屬性來獲得。編譯器旗標可以在ast
module 中搜尋有PyCF_
前綴的名稱。引數 optimize 用來指定編譯器的最佳化級別;預設值
-1
選擇與直譯器的-O
選項相同的最佳化級別。其他級別為0
(沒有最佳化;__debug__
為真值)、1
(assert 被刪除,__debug__
為假值)或2
(說明字串 (docstring) 也被刪除)。如果編譯的原始碼無效,此函式會引發
SyntaxError
,如果原始碼包含 null bytes,則會引發ValueError
。如果您想解析 Python 程式碼為 AST 運算式,請參閱
ast.parse()
。引發一個附帶引數
source
、filename
的稽核事件compile
。備註
在
'single'
或'eval'
模式編譯多行程式碼時,輸入必須以至少一個換行符結尾。這使code
module 更容易檢測陳述式的完整性。警告
如果編譯足夠大或者足夠複雜的字串成 AST 物件時,Python 直譯器會因為 Python AST 編譯器的 stack 深度限制而崩潰。
在 3.2 版的變更: 允許使用 Windows 和 Mac 的換行符號。此外,在
'exec'
模式不需要以換行符號結尾。增加了 optimize 參數。在 3.5 版的變更: 在之前的版本,source 中包含 null bytes 會引發
TypeError
。Added in version 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)
If the argument is a string, it must contain either a real part (in the same format as for
float()
) or an imaginary part (in the same format but with a'j'
or'J'
suffix), or both real and imaginary parts (the sign of the imaginary part is mandatory in this case). The string can optionally be surrounded by whitespaces and the round parentheses'('
and')'
, which are ignored. The string must not contain whitespace between'+'
,'-'
, the'j'
or'J'
suffix, and the decimal number. For example,complex('1+2j')
is fine, butcomplex('1 + 2j')
raisesValueError
. More precisely, the input must conform to thecomplexvalue
production rule in the following grammar, after parentheses and leading and trailing whitespace characters are removed:complexvalue ::=
floatvalue
|floatvalue
("j" | "J") |floatvalue
sign
absfloatvalue
("j" | "J")If the argument is a number, the constructor serves as a numeric conversion like
int
andfloat
. For a general Python objectx
,complex(x)
delegates tox.__complex__()
. If__complex__()
is not defined then it falls back to__float__()
. If__float__()
is not defined then it falls back to__index__()
.If two arguments are provided or keyword arguments are used, each argument may be any numeric type (including complex). If both arguments are real numbers, return a complex number with the real component real and the imaginary component imag. If both arguments are complex numbers, return a complex number with the real component
real.real-imag.imag
and the imaginary componentreal.imag+imag.real
. If one of arguments is a real number, only its real component is used in the above expressions.If all arguments are omitted, returns
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(**kwarg)
- class dict(mapping, **kwarg)
- class dict(iterable, **kwarg)
建立一個新的 dictionary(字典)。
dict
物件是一個 dictionary class。參見dict
和 映射类型 --- dict 來瞭解這個 class。其他容器型別,請參見內建的
list
、set
和tuple
class,以及collections
module。
- 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
)。
- 回傳:
被求值表达式的求值结果。
- 引发:
Syntax errors are reported as exceptions.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals mappings as global and local namespace. If the globals dictionary is present and does not contain a value for the key
__builtins__
, a reference to the dictionary of the built-in modulebuiltins
is inserted under that key before expression is parsed. That way you can control what builtins are available to the executed code by inserting your own__builtins__
dictionary into globals before passing it toeval()
. If the locals mapping is omitted it defaults to the globals dictionary. If both mappings are omitted, the expression is executed with the globals and locals in the environment whereeval()
is called. Note, eval() will only have access to the nested scopes (non-locals) in the enclosing environment if they are already referenced in the scope that is callingeval()
(e.g. via anonlocal
statement).範例:
>>> x = 1 >>> eval('x+1') 2
這個函式也可以用來執行任意程式碼物件(如被
compile()
建立的那些)。這種情況下,傳入的引數是程式碼物件而不是字串。如果編譯該物件時的 mode 引數是'exec'
,那麼eval()
回傳值為None
。提示:
exec()
函式支援動態執行陳述式。globals()
和locals()
函式分別回傳當前的全域性和局部性 dictionary,它們對於將引數傳遞給eval()
或exec()
可能會方便許多。如果給定來源是一個字串,那麼其前後的空格和定位字元會被移除。
另外可以參閱
ast.literal_eval()
,該函式可以安全執行僅包含文字的運算式字串。引發一個附帶引數
code_object
的稽核事件exec
。在 3.13 版的變更: The globals and locals arguments can now be passed as keywords.
在 3.13 版的變更: The semantics of the default locals namespace have been adjusted as described for the
locals()
builtin.
- exec(source, /, globals=None, locals=None, *, closure=None)¶
This function supports dynamic execution of Python code. source must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that's executed is expected to be valid as file input (see the section 檔案輸入 in the Reference Manual). Be aware that the
nonlocal
,yield
, andreturn
statements may not be used outside of function definitions even within the context of code passed to theexec()
function. The return value isNone
.In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary.
備註
When
exec
gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition. This means functions and classes defined in the executed code will not be able to access variables assigned at the top level (as the "top level" variables are treated as class variables in a class definition).如果 globals dictionary 不包含
__builtins__
鍵值,則將為該鍵插入對內建builtins
module dictionary 的引用。這麼一來,在將__builtins__
dictionary 傳入exec()
之前,你可以透過將它插入 globals 來控制你需要哪些內建函式來執行程式碼。closure 引數會指定一個閉包 (closure) — 它是一個 cellvar(格變數)的 tuple。只有在 object 是一個含有自由變數 (free variable) 的程式碼物件時,它才有效。Tuple 的長度必須與程式碼物件所引用的自由變數數量完全匹配。
引發一個附帶引數
code_object
的稽核事件exec
。備註
The built-in functions
globals()
andlocals()
return the current global and local namespace, respectively, which may be useful to pass around for use as the second and third argument toexec()
.備註
The default locals act as described for function
locals()
below. Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()
returns.在 3.11 版的變更: 增加了 closure 參數。
在 3.13 版的變更: The globals and locals arguments can now be passed as keywords.
在 3.13 版的變更: The semantics of the default locals namespace have been adjusted as described for the
locals()
builtin.
- 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
]digitpart
floatnumber ::=number
[exponent
] absfloatvalue ::=floatnumber
|infinity
|nan
floatvalue ::= [sign
]absfloatvalue
字母大小寫不影響,例如,"inf"、"Inf"、"INFINITY"、"iNfINity" 都可以表示正無窮大。
否則,如果引數是整數或浮點數,則回傳具有相同值(在 Python 浮點精度範圍內)的浮點數。如果引數在 Python 浮點精度範圍外,則會引發
OverflowError
。對於一般的 Python 物件
x
,float(x)
會委派給x.__float__()
。如果未定義__float__()
則會回退到__index__()
。如果沒有引數,則回傳
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=set())
回傳一個新的
frozenset
物件,它包含選擇性引數 iterable 中的元素。frozenset
是一個內建的 class。有關此 class 的文件,請參閱frozenset
和 集合类型 --- set, frozenset。請參閱內建的
set
、list
、tuple
和dict
class,以及collections
module 來了解其它的容器。
- 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) 參數。有關更多資訊,請參閱常見問答集中的僅限位置參數條目。此函式會被
site
module 加入到內建命名空間。
- hex(x)¶
將整數轉換為以 "0x" 為前綴的小寫十六進位制字串。如果 x 不是 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()
值。CPython 實作細節: 這是該物件在記憶體中的位址。
引發一個附帶引數
id
的稽核事件builtins.id
。
- input()¶
- input(prompt)
如果有提供 prompt 引數,則將其寫入標準輸出,末尾不帶換行符。接下來,該函式從輸入中讀取一行,將其轉換為字串(去除末尾的換行符)並回傳。當讀取到 EOF 時,則引發
EOFError
。例如:>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
如果載入了
readline
module,input()
將使用它來提供複雜的行編輯和歷史記錄功能。引發一個附帶引數
prompt
的稽核事件builtins.input
。引發一個附帶引數
result
的稽核事件builtins.input/result
。
- class int(number=0, /)¶
- class int(string, /, base=10)
Return an integer object constructed from a number or a string, or return
0
if no arguments are given.例如:
>>> 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
If the argument defines
__int__()
,int(x)
returnsx.__int__()
. If the argument defines__index__()
, it returnsx.__index__()
. For floating point numbers, this truncates towards zero.如果引數不是數字或如果有給定 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()
no longer delegates to the__trunc__()
method.
- isinstance(object, classinfo)¶
如果 object 引數是 classinfo 引數的實例,或者是(直接、間接或 virtual)subclass 的實例,則回傳
True
。如果 object 不是給定型別的物件,函式始終回傳False
。如果 classinfo 是包含物件型別的 tuple(或多個遞迴 tuple)或一個包含多種型別的 union 类型,若 object 是其中的任何一個物件的實例則回傳True
。如果 classinfo 既不是型別,也不是型別 tuple 或型別的遞迴 tuple,那麼會引發TypeError
異常。若是先前檢查已經成功,TypeError
可能不會再因為不合格的型別而被引發。在 3.10 版的變更: classinfo 可以是一個 union 类型。
- issubclass(class, classinfo)¶
如果 class 是 classinfo 的 subclass(直接、間接或 virtual),則回傳
True
。classinfo 可以是 class 物件的 tuple(或遞迴地其他類似 tuple)或是一個 union 类型,此時若 class 是 classinfo 中任一元素的 subclass 時則回傳True
。其他情況,會引發TypeError
。在 3.10 版的變更: classinfo 可以是一個 union 类型。
- iter(object)¶
- iter(object, sentinel)
回傳一個 iterator 物件。根據是否存在第二個引數,第一個引數的意義是非常不同的。如果沒有第二個引數,object 必須是支援 iterable 協定(有
__iter__()
method)的集合物件,或必須支援序列協定(有__getitem__()
方法,且數字引數從0
開始)。如果它不支援這些協定,會引發TypeError
。如果有第二個引數 sentinel,那麼 object 必須是可呼叫的物件,這種情況下生成的 iterator,每次疊代呼叫__next__()
時會不帶引數地呼叫 object;如果回傳的結果是 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(s)¶
回傳物件的長度(元素個數)。引數可以是序列(如 string、bytes、tuple、list 或 range)或集合(如 dictionary、set 或 frozen set)。
CPython 實作細節: 如果物件長度大於
sys.maxsize
,像是range(2 ** 100)
,則len
會引發OverflowError
。
- class list
- class list(iterable)
除了是函式,
list
也是可變序列型別,詳情請參閱 List(串列) 和 序列类型 --- list, tuple, range。
- locals()¶
Return a mapping object representing the current local symbol table, with variable names as the keys, and their currently bound references as the values.
At module scope, as well as when using
exec()
oreval()
with a single namespace, this function returns the same namespace asglobals()
.At class scope, it returns the namespace that will be passed to the metaclass constructor.
When using
exec()
oreval()
with separate local and global arguments, it returns the local namespace passed in to the function call.In all of the above cases, each call to
locals()
in a given frame of execution will return the same mapping object. Changes made through the mapping object returned fromlocals()
will be visible as assigned, reassigned, or deleted local variables, and assigning, reassigning, or deleting local variables will immediately affect the contents of the returned mapping object.In an optimized scope (including functions, generators, and coroutines), each call to
locals()
instead returns a fresh dictionary containing the current bindings of the function's local variables and any nonlocal cell references. In this case, name binding changes made via the returned dict are not written back to the corresponding local variables or nonlocal cell references, and assigning, reassigning, or deleting local variables and nonlocal cell references does not affect the contents of previously returned dictionaries.Calling
locals()
as part of a comprehension in a function, generator, or coroutine is equivalent to calling it in the containing scope, except that the comprehension's initialised iteration variables will be included. In other scopes, it behaves as if the comprehension were running as a nested function.Calling
locals()
as part of a generator expression is equivalent to calling it in a nested generator function.在 3.12 版的變更: The behaviour of
locals()
in a comprehension has been updated as described in PEP 709.在 3.13 版的變更: As part of PEP 667, the semantics of mutating the mapping objects returned from this function are now defined. The behavior in optimized scopes is now as described above. Aside from being defined, the behaviour in other scopes remains unchanged from previous versions.
- map(function, iterable, *iterables)¶
產生一個將 function 應用於 iterable 中所有元素,並收集回傳結果的 iterator。如果傳遞了額外的 iterables 引數,則 function 必須接受相同個數的引數,並使用所有從 iterables 中同時獲取的元素。當有多個 iterables 時,最短的 iteratable 耗盡時 iterator 也會結束。如果函式的輸入已經被編排為引數的 tuple,請參閱
itertools.starmap()
。
- 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(記憶體檢視)」物件。有關詳細資訊,請參閱内存视图。
- 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
。
- oct(x)¶
將一個整數轉變為一個前綴為 "0o" 的八進位制字串。回傳結果是一個有效的 Python 運算式。如果 x 不是 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 引數,則預設的緩衝策略會運作如下:二進制檔案會以固定大小的區塊進行緩衝;緩衝區的大小是使用啟發式嘗試 (heuristic trying) 來決定底層設備的「區塊大小」,並會回退到
io.DEFAULT_BUFFER_SIZE
。在許多系統上,緩衝區的長度通常為 4096 或 8192 個位元組。「互動式」文字檔(
isatty()
回傳True
的檔案)會使用列緩衝。其他文字檔則使用上述的二進制檔案緩衝策略。
encoding 是用於解碼或編碼檔案的編碼系統之名稱。它只應該在文字模式下使用。預設的編碼系統會取決於平台(根據
locale.getencoding()
回傳的內容),但 Python 支援的任何 text encoding(文字編碼)都是可以使用的。關於支援的編碼系統清單,請參閱codecs
module。errors 是一個選擇性的字串,用於指定要如何處理編碼和解碼的錯誤——它不能在二進制模式下使用。有許多不同的標準錯誤處理程式(error handler,在错误处理方案有列出清單),不過任何已註冊到
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
。引發一個附帶引數
file
、model
、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(c)¶
對於代表單個 Unicode 字元的字串,回傳代表它 Unicode 編碼位置的整數。例如
ord('a')
回傳整數97
、ord('€')
(歐元符號)回傳8364
。這是chr()
的逆函式。
- pow(base, exp, mod=None)¶
回傳 base 的 exp 次方;如果 mod 存在,則回傳 base 的 exp 次方對 mod 取餘數(比直接呼叫
pow(base, exp) % mod
計算更高效)。兩個引數形式的pow(exp, exp)
等價於次方運算子:base**exp
。The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For
int
operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example,pow(10, 2)
returns100
, butpow(10, -2)
returns0.01
. For a negative base of typeint
orfloat
and a non-integral exponent, a complex result is delivered. For example,pow(-9, 0.5)
returns a value close to3j
. Whereas, for a negative base of typeint
orfloat
with an integral exponent, a float result is delivered. For example,pow(-9, 2.0)
returns81.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 版的變更: 特征属性对象的文档字符串现在是可写的。
- class range(stop)
- class range(start, stop, step=1)
虽然被称为函数,但
range
实际上是一个不可变的序列类型,参见在 range 对象 与 序列类型 --- 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(seq)¶
返回一个反向的 iterator。 seq 必须是一个具有
__reversed__()
方法或是支持序列协议(具有__len__()
方法和从0
开始的整数参数的__getitem__()
方法)的对象。
- round(number, ndigits=None)¶
返回 number 舍入到小数点后 ndigits 位精度的值。 如果 ndigits 被省略或为
None
,则返回最接近输入值的整数。对于支持
round()
方法的内置类型,结果值会舍入至最接近的 10 的负 ndigits 次幂的倍数;如果与两个倍数同样接近,则选用偶数。因此,round(0.5)
和round(-0.5)
均得出0
而round(1.5)
则为2
。ndigits 可为任意整数值(正数、零或负数)。如果省略了 ndigits 或为None
,则返回值将为整数。否则返回值与 number 的类型相同。对于一般的 Python 对象
number
,round
将委托给number.__round__
。備註
对浮点数执行
round()
的行为可能会令人惊讶:例如,round(2.675, 2)
将给出2.67
而不是期望的2.68
。 这不算是程序错误:这一结果是由于大多数十进制小数实际上都不能以浮点数精确地表示。 请参阅 浮點數運算:問題與限制 了解更多信息。
- class set
- class set(iterable)
返回一个新的
set
对象,可以选择带有从 iterable 获取的元素。set
是一个内置类型。 请查看set
和 集合类型 --- set, frozenset 获取关于这个类的文档。有关其他容器请参看内置的
frozenset
,list
,tuple
和dict
类,以及collections
模块。
- setattr(object, name, value)¶
本函数与
getattr()
相对应。其参数为一个对象、一个字符串和一个任意值。字符串可以为某现有属性的名称,或为新属性。只要对象允许,函数会将值赋给属性。如setattr(x, 'foobar', 123)
等价于x.foobar = 123
。name 无需为在 标识符和关键字 中定义的 Python 标识符除非对象选择强制这样做,例如在一个自定义的
__getattribute__()
中或是通过__slots__
。 一个名称不为标识符的属性将不可使用点号标记来访问,但是可以通过getattr()
等来访问。
- class slice(stop)¶
- class slice(start, stop, step=None)
返回一个表示由
range(start, stop, step)
指定的索引集的 slice 对象。 start 和 step 参数默认为None
。- start¶
- stop¶
- step¶
切片对象具有只读的数据属性
start
,stop
和step
,它们将简单地返回相应的参数值(或其默认值)。 它们没有其他显式的功能;但是,它们会被 NumPy 和其他第三方包所使用。
当使用扩展索引语法时也会生成切片对象。 例如:
a[start:stop:step]
或a[start:stop, i]
。 请参阅itertools.islice()
了解返回 iterator 的替代版本。
- sorted(iterable, /, *, key=None, reverse=False)¶
根据 iterable 中的项返回一个新的已排序列表。
有兩個選擇性引數,只能使用關鍵字引數來指定。
key 指定带有单个参数的函数,用于从 iterable 的每个元素中提取用于比较的键 (例如
key=str.lower
)。 默认值为None
(直接比较元素)。reverse 为一个布尔值。 如果设为
True
,则每个列表元素将按反向顺序比较进行排序。使用
functools.cmp_to_key()
可将老式的 cmp 函数转换为 key 函数。内置的
sorted()
确保是稳定的。 如果一个排序确保不会改变比较结果相等的元素的相对顺序就称其为稳定的 --- 这有利于进行多重排序(例如先按部门、再按薪级排序)。排序算法只使用
<
在项目之间比较。 虽然定义一个__lt__()
方法就足以进行排序,但 PEP 8 建议实现所有六个 富比较 。 这将有助于避免在与其他排序工具(如max()
)使用相同的数据时出现错误,这些工具依赖于不同的底层方法。实现所有六个比较也有助于避免混合类型比较的混乱,因为混合类型比较可以调用反射到__gt__()
的方法。有关排序示例和简要排序教程,请参阅 排序技法 。
- @staticmethod¶
将方法转换为静态方法。
静态方法不会接收隐式的第一个参数。要声明一个静态方法,请使用此语法
class C: @staticmethod def f(arg1, arg2, argN): ...
@staticmethod
語法是一個函式 decorator - 參見 函式定義 中的詳細介紹。静态方式既可以在类上调用 (如
C.f()
),也可以在实例上调用 (如C().f()
)。 此外,静态方法 descriptor 也属于可调用对象,因而它们可以在类定义中使用 (如f()
)。Python 的静态方法与 Java 或 C++ 类似。另请参阅
classmethod()
,可用于创建另一种类构造函数。像所有装饰器一样,也可以像常规函数一样调用
staticmethod
,并对其结果执行某些操作。比如某些情况下需要从类主体引用函数并且您希望避免自动转换为实例方法。对于这些情况,请使用此语法:def regular_function(): ... class C: method = staticmethod(regular_function)
關於 static method 的更多資訊,請參考 標準型別階層。
在 3.10 版的變更: 静态方法继承了方法的多个属性(
__module__
、__name__
、__qualname__
、__doc__
和__annotations__
),还拥有一个新的__wrapped__
属性,并且现在还可以作为普通函数进行调用。
- class str(object='')
- class str(object=b'', encoding='utf-8', errors='strict')
返回一个
str
版本的 object 。有关详细信息,请参阅str()
。str
是内置字符串 class 。更多关于字符串的信息查看 文本序列类型 --- str。
- sum(iterable, /, start=0)¶
从 start 开始自左向右对 iterable 的项求和并返回总计值。 iterable 的项通常为数字,而 start 值则不允许为字符串。
对某些用例来说,存在
sum()
的更好替代。 拼接字符串序列的更好更快方式是调用''.join(sequence)
。 要以扩展精度对浮点值求和,请参阅math.fsum()
。 要拼接一系列可迭代对象,请考虑使用itertools.chain()
。在 3.8 版的變更: start 參數可被指定為關鍵字引數。
在 3.12 版的變更: Summation of floats switched to an algorithm that gives higher accuracy and better commutativity on most builds.
- class super¶
- class super(type, object_or_type=None)
返回一个代理对象,它会将方法调用委托给 type 的父类或兄弟类。 这对于访问已在类中被重写的继承方法很有用。
object_or_type 确定要用于搜索的 method resolution order。 搜索会从 type 之后的类开始。
举例来说,如果 object_or_type 的
__mro__
为D -> B -> C -> A -> object
并且 type 的值为B
,则super()
将会搜索C -> A -> object
。object_or_type 的
__mro__
属性列出了getattr()
和super()
所共同使用的方法解析搜索顺序。 该属性是动态的并可在任何继承层级结构发生更新时被改变。如果省略第二个参数,则返回的超类对象是未绑定的。 如果第二个参数为一个对象,则
isinstance(obj, type)
必须为真值。 如果第二个参数为一个类型,则issubclass(type2, type)
必须为真值(这适用于类方法)。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.)super 有两个典型用例。 在具有单继承的类层级结构中,super 可用来引用父类而不必显式地指定它们的名称,从而令代码更易维护。 这种用法与其他编程语言中 super 的用法非常相似。
第二个用例是在动态执行环境中支持协作多重继承。 此用例为 Python 所独有而不存在于静态编码语言或仅支持单继承的语言当中。 这使用实现“菱形图”成为可能,即有多个基类实现相同的方法。 好的设计强制要求这样的方法在每个情况下都具有相同的调用签名(因为调用顺序是在运行时确定的,也因为这个顺序要适应类层级结构的更改,还因为这个顺序可能包括在运行时之前未知的兄弟类)。
对于以上两个用例,典型的超类调用看起来是这样的:
class C(B): def method(self, arg): super().method(arg) # This does the same thing as: # super(C, self).method(arg)
除了方法查找之外,
super()
也可用于属性查找。 一个可能的应用场合是在上级或同级类中调用 描述器。请注意
super()
被实现为为显式的带点号属性查找的绑定过程的组成部分,例如super().__getitem__(name)
。 它做到这一点是通过实现自己的__getattribute__()
方法以便能够按支持协作多重继承的可预测的顺序来搜索类。 相应地,super()
在像super()[name]
这样使用语句或运算符进行隐式查找时则是未定义的。还要注意的是,除了零个参数的形式以外,
super()
并不限于在方法内部使用。 两个参数的形式明确指定参数并进行相应的引用。 零个参数的形式仅适用于类定义内部,因为编译器需要填入必要的细节以正确地检索到被定义的类,还需要让普通方法访问当前实例。对于有关如何使用
super()
来如何设计协作类的实用建议,请参阅 使用 super() 的指南。
- class tuple
- class tuple(iterable)
虽然被称为函数,但
tuple
实际上是一个不可变的序列类型,参见在 元组 与 序列类型 --- list, tuple, range 中的文档说明。
- class type(object)¶
- class type(name, bases, dict, **kwds)
传入一个参数时,返回 object 的类型。 返回值是一个 type 对象,通常与
object.__class__
所返回的对象相同。推荐使用
isinstance()
内置函数来检测对象的类型,因为它会考虑子类的情况。传入三个参数时,返回一个新的 type 对象。 这在本质上是
class
语句的一种动态形式,name 字符串即类名并会成为__name__
属性;bases 元组包含基类并会成为__bases__
属性;如果为空则会添加所有类的终极基类object
。 dict 字典包含类主体的属性和方法定义;它在成为__dict__
属性之前可能会被拷贝或包装。 下面两条语句会创建相同的type
对象:>>> class X: ... a = 1 ... >>> X = type('X', (), dict(a=1))
另請參閱 类型对象。
提供给三参数形式的关键字参数会被传递给适当的元类机制 (通常为
__init_subclass__()
),相当于类定义中关键字 (除了 metaclass) 的行为方式。另請參閱 自定义类创建。
在 3.6 版的變更:
type
的子类如果未重写type.__new__
,将不再能使用一个参数的形式来获取对象的类型。
- vars()¶
- vars(object)
返回模块、类、实例或任何其它具有
__dict__
属性的对象的__dict__
属性。模块和实例这样的对象具有可更新的
__dict__
属性;但是,其它对象的__dict__
属性可能会设为限制写入(例如,类会使用types.MappingProxyType
来防止直接更新字典)。Without an argument,
vars()
acts likelocals()
.如果指定了一个对象但它没有
__dict__
属性(例如,当它所属的类定义了__slots__
属性时)则会引发TypeError
异常。在 3.13 版的變更: The result of calling this function without an argument has been updated as described for the
locals()
builtin.
- zip(*iterables, strict=False)¶
在多个迭代器上并行迭代,从每个迭代器返回一个数据项组成元组。
例如:
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): ... print(item) ... (1, 'sugar') (2, 'spice') (3, 'everything nice')
更正式的说法:
zip()
返回元组的迭代器,其中第 i 个元组包含的是每个参数迭代器的第 i 个元素。不妨换一种方式认识
zip()
:它会把行变成列,把列变成行。这类似于 矩阵转置 。zip()
是延迟执行的:直至迭代时才会对元素进行处理,比如for
循环或放入list
中。值得考虑的是,传给
zip()
的可迭代对象可能长度不同;有时是有意为之,有时是因为准备这些对象的代码存在错误。Python 提供了三种不同的处理方案:默认情况下,
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
参数,所有导致可迭代对象长度不同的错误都会被抑制,这可能会在程序的其他地方表现为难以发现的错误。为了让所有的可迭代对象具有相同的长度,长度较短的可用常量进行填充。这可由
itertools.zip_longest()
来完成。
极端例子是只有一个可迭代对象参数,
zip()
会返回一个一元组的迭代器。如果未给出参数,则返回一个空的迭代器。小技巧:
可确保迭代器的求值顺序是从左到右的。这样就能用
zip(*[iter(s)]*n, strict=True)
将数据列表按长度 n 进行分组。这将重复 相同 的迭代器n
次,输出的每个元组都包含n
次调用迭代器的结果。这样做的效果是把输入拆分为长度为 n 的块。zip()
与*
运算符相结合可以用来拆解一个列表:>>> 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
语句的语义,但是 强烈 不建议这样做,因为使用导入钩子 (参见 PEP 302) 通常更容易实现同样的目标,并且不会导致代码问题,因为许多代码都会假定所用的是默认实现。 同样也不建议直接使用__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
的结果将为与以下代码作用相同的字节码:spam = __import__('spam', globals(), locals(), [], 0)
语句
import spam.ham
的结果将为以下调用:spam = __import__('spam.ham', globals(), locals(), [], 0)
请注意在这里
__import__()
是如何返回顶层模块的,因为这是通过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
现在将被忽略。
註解