內建函式¶
Python 直譯器有內建多個可隨時使用的函式和型別。以下按照英文字母排序列出。
內建函式 |
|||
---|---|---|---|
- aiter(async_iterable)¶
Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling
x.__aiter__()
.Note: Unlike
iter()
,aiter()
has no 2-argument variant.在 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)
When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.
This is the async variant of the
next()
builtin, and behaves similarly.This calls the
__anext__()
method of async_iterator, returning an awaitable. Awaiting this returns the next value of the iterator. If default is given, it is returned if the iterator is exhausted, otherwiseStopAsyncIteration
is raised.在 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(x=False)¶
回傳一個布林值,即
True
或者False
。x 使用標準的真值測試程序來轉換。如果 x 為假或者被省略,則回傳False
;其他情況回傳True
。bool
class(類別)是int
的 subclass(子類別)(參見 Numeric Types --- int, float, complex),其他 class 不能繼承自它。它只有False
和True
兩個實例(參見 Boolean Type - bool)。在 3.7 版的變更: x is now a positional-only parameter.
- breakpoint(*args, **kws)¶
This function drops you into the debugger at the call site. Specifically, it calls
sys.breakpointhook()
, passingargs
andkws
straight through. By default,sys.breakpointhook()
callspdb.set_trace()
expecting no arguments. In this case, it is purely a convenience function so you don't have to explicitly importpdb
or type as much code to enter the debugger. However,sys.breakpointhook()
can be set to some other function andbreakpoint()
will automatically call that, allowing you to drop into the debugger of choice. Ifsys.breakpointhook()
is not accessible, this function will raiseRuntimeError
.By default, the behavior of
breakpoint()
can be changed with thePYTHONBREAKPOINT
environment variable. Seesys.breakpointhook()
for usage details.Note that this is not guaranteed if
sys.breakpointhook()
has been replaced.引發一個附帶引數
breakpointhook
的稽核事件builtins.breakpoint
。在 3.7 版新加入.
- class bytearray(source=b'')
- class bytearray(source, encoding)
- class bytearray(source, encoding, errors)
回傳一個新的 bytes 陣列。
bytearray
class 是一個可變的整數序列,包含範圍為 0 <= x < 256 的整數。它有可變序列大部分常見的 method(如在 Mutable Sequence Types 中所述),同時也有bytes
型別大部分的 method,參見 Bytes and Bytearray Operations。選擇性參數 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 Objects。
- class bytes(source=b'')
- class bytes(source, encoding)
- class bytes(source, encoding, errors)
回傳一個新的 "bytes" 物件,會是一個元素是範圍為
0 <= x < 256
整數的不可變序列。bytes
是bytearray
的不可變版本 — 它的同樣具備不改變物件的 method,也有相同的索引和切片操作。因此,建構函式的引數和
bytearray()
相同。Bytes 物件還可以用文字建立,參見 String and Bytes literals。
可參考 Binary Sequence Types --- bytes, bytearray, memoryview、Bytes Objects 和 Bytes and Bytearray Operations。
- callable(object)¶
如果引數 object 是可呼叫的,回傳
True
,否則回傳False
。如果回傳True
,呼叫仍可能會失敗;但如果回傳False
,則呼叫 object 肯定會失敗。注意 class 是可呼叫的(呼叫 class 會回傳一個新的實例);如果實例的 class 有定義__call__()
method,則它是可呼叫的。在 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 can now wrap other descriptors such as
property()
.在 3.10 版的變更: Class methods now inherit the method attributes (
__module__
,__name__
,__qualname__
,__doc__
and__annotations__
) and have a new__wrapped__
attribute.在 3.11 版的變更: Class methods can no longer wrap other descriptors such as
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
則會被印出來)。The optional arguments flags and dont_inherit control which compiler options should be activated and which future features should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling
compile()
. If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it -- the flags (future features and compiler options) in the surrounding code are ignored.編譯器選項和 future 陳述式使用 bits 來表示,可以一起被位元操作 OR 來表示複數個選項。需要被具體定義特徵的位元域可以透過
__future__
module 中_Feature
實例中的compiler_flag
屬性來獲得。編譯器旗標可以在ast
module 中搜尋有PyCF_
前綴的名稱。引數 optimize 用來指定編譯器的最佳化級別;預設值
-1
選擇與直譯器的-O
選項相同的最佳化級別。其他級別為0
(沒有最佳化;__debug__
為真值)、1
(assert 被刪除,__debug__
為假值)或2
(文件字串也被刪除)。如果編譯的原始碼無效,此函式會觸發
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
異常。在 3.8 版新加入:
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
can now be passed in flags to enable support for top-levelawait
,async for
, andasync with
.
- class complex(real=0, imag=0)¶
- class complex(string)
回傳值為 real + imag*1j 的複數,或將字串、數字轉換為複數。如果第一個引數是字串,則它被視為一個複數,並且函式呼叫時不得有第二個引數。第二個引數絕對不能是字串。每個引數都可以是任意的數值型別(包括複數)。如果省略了 imag,則預設值為零,建構函式會像
int
和float
一樣進行數值轉換。如果兩個引數都省略,則回傳0j
。對於一般的 Python 物件
x
,complex(x)
指派給x.__complex__()
。如果未定義__complex__()
則會回退使用__float__()
。如果未定義__float__()
則會回退使用__index__()
。備註
當轉換自一字串時,字串在
+
或-
運算子的周圍必須不能有空格。例如complex('1+2j')
是有效的,但complex('1 + 2j')
會觸發ValueError
。複數型別在 Numeric Types --- int, float, complex 中有相關描述。
在 3.6 版的變更: 可以使用底線將程式碼文字中的數字進行分組。
在 3.8 版的變更: Falls back to
__index__()
if__complex__()
and__float__()
are not defined.
- 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
和 Mapping Types --- dict 來瞭解這個 class。其他容器型別,請參見內建的
list
、set
和tuple
class,以及collections
module。
- dir()¶
- dir(object)
如果沒有引數,則回傳當前本地作用域中的名稱列表。如果有引數,它會嘗試回傳該物件的有效屬性列表。
如果物件有一個名為
__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(expression, globals=None, locals=None)¶
引數是一個字串,以及選擇性的 globals 和 locals。如果有提供選擇性引數,globals 必須是一個 dictionary。locals 可以是任何映射 (mapping) 物件。
expression 引數被剖析並執行成 Python 運算式(技術上而言,是條件列表),globals 和 locals dictionaries 分別用作全域性和本地命名空間。如果 globals dictionary 存在但缺少
__builtins__
的鍵值,那 expression 被剖析之前,將為該鍵插入對內建builtins
module dictionary 的引用。這麼一來,在將__builtins__
傳入eval()
之前,你可以透過將它插入 globals 來控制你需要哪些內建函式。如果 locals 被省略,那它的預設值是 globals dictionary。如果兩個 dictionary 變數都被省略,則在eval()
被呼叫的環境中執行運算式。請注意,eval() 在封閉環境中無法存取巢狀域 (non-locals)。The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>> x = 1 >>> eval('x+1') 2
這個函式也可以用來執行任意程式碼物件(如被
compile()
建立的那些)。這種情況下,傳入的引數是程式碼物件而不是字串。如果編譯該物件時的 mode 引數是'exec'
,那麼eval()
回傳值為None
。提示:
exec()
函式支援動態執行陳述式。globals()
和locals()
函式分別回傳當前的全域性和局部性 dictionary,它們對於將引數傳遞給eval()
或exec()
可能會方便許多。If the given source is a string, then leading and trailing spaces and tabs are stripped.
另外可以參閱
ast.literal_eval()
,該函式可以安全執行僅包含文字的運算式字串。引發一個附帶引數
code_object
的稽核事件exec
。
- exec(object, globals=None, locals=None, /, *, closure=None)¶
這個函式支援動態執行 Python 程式碼。object 必須是字串或者程式碼物件。如果是字串,那麼該字串將被剖析為一系列 Python 陳述式並執行(除非發生語法錯誤)。[1] 如果是程式碼物件,它將被直接執行。無論哪種情況,被執行的程式碼都需要和檔案輸入一樣是有效的(可參考手冊中關於 檔案輸入 的章節)。請注意,即使在傳遞給
exec()
函式的程式碼的上下文中,nonlocal
、yield
和return
陳述式也不能在函式之外使用。該函式回傳值是None
。無論哪種情況,如果省略了選擇性引數,程式碼將在當前作用域內執行。如果只提供了 globals 引數,就必須是 dictionary 型別,而且會被用作全域性和本地變數。如果同時提供了 globals 和 locals 引數,它們分別被用作全域性和本地變數。如果提供了 locals 引數,則它可以是任何映射物件。請記住在 module 層級中全域性和本地變數是相同的 dictionary。如果 exec 有兩個不同的 globals 和 locals 物件,程式碼就像嵌入在 class 定義中一樣執行。
如果 globals dictionary 不包含
__builtins__
鍵值,則將為該鍵插入對內建builtins
module dictionary 的引用。因此,在將執行的程式碼傳遞給exec()
之前,可以通過將自己的__builtins__
dictionary 插入到 globals 中來控制可以使用哪些內建程式碼。The closure argument specifies a closure--a tuple of cellvars. It's only valid when the object is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.
引發一個附帶引數
code_object
的稽核事件exec
。備註
預設情況下,locals 的行為如下面
locals()
函式描述的一樣:不要試圖改變預設的 locals dictionary。如果您想在exec()
函式回傳時知道程式碼對 locals 的變動,請明確地傳遞 locals dictionary 。在 3.11 版的變更: 增加了 closure 參數。
- 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(x=0.0)¶
回傳從數字或字串 x 生成的浮點數。
如果引數是字串,則它必須是包含十進位制數字的字串,字串前面可以有符號,之前也可以有空格。選擇性的符號有
'+'
和'-'
;'+'
對建立的值沒有影響。引數也可以是 NaN(非數字)或正負無窮大的字串。確切地說,除去首尾的空格後,輸入必須遵循以下語法中floatvalue
的生成規則:sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" digitpart ::= `!digit` (["_"] `!digit`)* number ::= [
digitpart
] "."digitpart
|digitpart
["."] exponent ::= ("e" | "E") ["+" | "-"]digitpart
floatnumber ::= number [exponent
] floatvalue ::= [sign
] (floatnumber
|infinity
|nan
)digit
是一個 Unicode 十進位數字(Unicode 一般分類Nd
中的字元)。字母大小寫都可以,例如,"inf"、"Inf"、"INFINITY"、"iNfINity" 都可以表示正無窮大。否則,如果引數是整數或浮點數,則回傳具有相同值(在 Python 浮點精度範圍內)的浮點數。如果引數在 Python 浮點精度範圍外,則會觸發
OverflowError
。對於一般的 Python 物件
x
,float(x)
指派給x.__float__()
。如果未定義__float__()
則回退使用__index__()
。如果沒有引數,則回傳
0.0
。例如:
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
Numeric Types --- int, float, complex 描述了浮點數型別。
在 3.6 版的變更: 可以使用底線將程式碼文字中的數字進行分組。
在 3.7 版的變更: x is now a positional-only parameter.
在 3.8 版的變更: Falls back to
__index__()
if__float__()
is not defined.
- 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 Types --- 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()
)。備註
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 retrieve it with
getattr()
.
- globals()¶
回傳代表當前 module 命名空間的 dictionary。對於在函式中的程式碼來說,這在定義函式時設定且不論該函式是在何處呼叫都會保持相同。
- hasattr(object, name)¶
該引數是一個物件和一個字串。如果字串是物件屬性之一的名稱,則回傳
True
,否則回傳False
。(此功能是通過呼叫getattr(object, name)
看是否有AttributeError
來實現的。)
- hash(object)¶
回傳該物件的雜湊值(如果它有的話)。雜湊值是整數。它們在 dictionary 查詢元素時用來快速比較 dictionary 的鍵。相同大小的數字數值有相同的雜湊值(即使它們型別不同,如 1 和 1.0)。
備註
For objects with custom
__hash__()
methods, note thathash()
truncates the return value based on the bit width of the host machine.
- help()¶
- help(request)
啟動內建的幫助系統(此函式主要以互動式使用)。如果沒有引數,直譯器控制臺裡會啟動互動式幫助系統。如果引數是一個字串,則在 module、函式、class、method、關鍵字或文件主題中搜索該字串,並在控制台上列印幫助資訊。如果引數是其他任意物件,則會生成該物件的幫助頁。
Note that if a slash(/) appears in the parameter list of a function when invoking
help()
, it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.該函式透過
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 實作細節: This is the address of the object in memory.
引發一個附帶引數
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(x=0)¶
- class int(x, base=10)
回傳一個使用數字或字串 x 建構的整數物件,或者在沒有引數時回傳
0
。如果 x 定義了__int__()
,int(x)
回傳x.__int__()
。如果 x 定義了__index__()
則回傳x.__index__()
。如果 x 定義了__trunc__()
則回傳x.__trunc__()
。對於浮點數則向零舍入。如果 x 不是數字或如果有給定 base,則 x 必須是個字串、
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)
是有效的。整數型別定義請參閱 Numeric Types --- int, float, complex。
在 3.4 版的變更: 如果 base 不是
int
的實例,但 base 物件有base.__index__
method,則會呼叫該 method 來獲取此進位制整數。以前的版本使用base.__int__
而不是base.__index__
。在 3.6 版的變更: 可以使用底線將程式碼文字中的數字進行分組。
在 3.7 版的變更: x is now a positional-only parameter.
在 3.8 版的變更: Falls back to
__index__()
if__int__()
is not defined.在 3.11 版的變更: The delegation to
__trunc__()
is deprecated.在 3.11 版的變更:
int
string inputs and string representations can be limited to help avoid denial of service attacks. AValueError
is raised when the limit is exceeded while converting a string x to anint
or when converting anint
into a string would exceed the limit. See the integer string conversion length limitation documentation.
- 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(object)¶
- iter(object, sentinel)
回傳一個 iterator 物件。根據是否存在第二個引數,第一個引數的意義是非常不同的。如果沒有第二個引數,object 必須是支援 iterable 協定(有
__iter__()
method)的集合物件,或必須支援序列協定(有__getitem__()
方法,且數字引數從0
開始)。如果它不支援這些協定,會觸發TypeError
。如果有第二個引數 sentinel,那麼 object 必須是可呼叫的物件,這種情況下生成的 iterator,每次疊代呼叫__next__()
時會不帶引數地呼叫 object;如果回傳的結果是 sentinel 則觸發StopIteration
,否則回傳呼叫結果。另請參閱 Iterator Types。
One useful application of the second form of
iter()
is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached: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 實作細節:
len
raisesOverflowError
on lengths larger thansys.maxsize
, such asrange(2 ** 100)
.
- class list
- class list(iterable)
除了是函式,
list
也是可變序列型別,詳情請參閱 List(串列) 和 Sequence Types --- list, tuple, range。
- locals()¶
更新並回傳表示當前本地符號表的 dictionary。在函式區塊而不是 class 區塊中呼叫
locals()
時會回傳自由變數。請注意,在 module 階層中,locals()
和globals()
是相同的 dictionary。備註
此 dictionary 的內容不應該被更動;更改可能不會影響直譯器使用的本地變數或自由變數的值。
- 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 版的變更: The key can be
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 版的變更: The key can be
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 並回傳對應的 file object。如果該檔案不能開啟,則觸發
OSError
。關於使用此函式的更多方法請參閱讀寫檔案。file 是一個 path-like object,是將被開啟之檔案的路徑(絕對路徑或者當前工作目錄的相當路徑),或是被封裝的整數檔案描述器 (file descriptor)。(如果有提供檔案描述器,它會隨著回傳的 I/O 物件關閉而關閉,除非 closefd 被設為
False
。)mode 是一個選擇性字串,用於指定開啟檔案的模式。預設值是
'r'
,這意味著它以文字模式開啟並讀取。其他常見模式有:寫入'w'
(會捨去已經存在的檔案)、唯一性創建'x'
、追加寫入'a'
(在一些 Unix 系統上,無論當前的檔案指標在什麼位置,所有 寫入都會追加到檔案末尾)。在文字模式,如果沒有指定 encoding,則根據電腦平臺來決定使用的編碼:呼叫locale.getencoding()
來獲取當前的本地編碼。(要讀取和寫入原始 bytes,請使用二進位制模式且不要指定 encoding。)可用的模式有:字元
意義
'r'
讀取(預設)
'w'
open for writing, truncating the file first
'x'
唯一性創建,如果文件已存在則會失敗
'a'
寫入,如果文件存在則在末尾追加寫入內容
'b'
binary mode(二進位模式)
't'
文字模式(預設)
'+'
更新(讀取並寫入)
預設的模式是
'r'
(開啟並讀取文字,同'rt'
)。對於二進位制寫入,'w+b'
模式開啟並把檔案內容變成 0 bytes,'r+b'
則不會捨棄原始內容。As mentioned in the 總覽, Python distinguishes between binary and text I/O. Files opened in binary mode (including
'b'
in the mode argument) return contents asbytes
objects without any decoding. In text mode (the default, or when't'
is included in the mode argument), the contents of the file are returned asstr
, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.備註
Python doesn't depend on the underlying operating system's notion of text files; all the processing is done by Python itself, and is therefore platform-independent.
buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable when writing in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this way applies for binary buffered I/O, but
TextIOWrapper
(i.e., files opened withmode='r+'
) would have another buffering. To disable buffering inTextIOWrapper
, consider using thewrite_through
flag forio.TextIOWrapper.reconfigure()
. When no buffering argument is given, the default buffering policy works as follows:Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on
io.DEFAULT_BUFFER_SIZE
. On many systems, the buffer will typically be 4096 or 8192 bytes long."Interactive" text files (files for which
isatty()
returnsTrue
) use line buffering. Other text files use the policy described above for binary files.
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever
locale.getencoding()
returns), but any text encoding supported by Python can be used. See thecodecs
module for the list of supported encodings.errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with
codecs.register_error()
is also valid. The standard names include:'strict'
to raise aValueError
exception if there is an encoding error. The default value ofNone
has the same effect.'ignore'
ignores errors. Note that ignoring encoding errors can lead to data loss.'replace'
causes a replacement marker (such as'?'
) to be inserted where there is malformed data.'surrogateescape'
will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when thesurrogateescape
error handler is used when writing data. This is useful for processing files in an unknown encoding.'xmlcharrefreplace'
is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference&#nnn;
.'backslashreplace'
replaces malformed data by Python's backslashed escape sequences.'namereplace'
(also only supported when writing) replaces unsupported characters with\N{...}
escape sequences.
newline determines how to parse newline characters from the stream. It can be
None
,''
,'\n'
,'\r'
, and'\r\n'
. It works as follows:When reading input from the stream, if newline is
None
, universal newlines mode is enabled. Lines in the input can end in'\n'
,'\r'
, or'\r\n'
, and these are translated into'\n'
before being returned to the caller. If it is''
, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.When writing output to the stream, if newline is
None
, any'\n'
characters written are translated to the system default line separator,os.linesep
. If newline is''
or'\n'
, no translation takes place. If newline is any of the other legal values, any'\n'
characters written are translated to the given string.
If closefd is
False
and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must beTrue
(the default); otherwise, an error will be raised.A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing
os.open
as opener results in functionality similar to passingNone
).新建立的檔案是不可繼承的。
下面的範例使用
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
The type of file object returned by the
open()
function depends on the mode. Whenopen()
is used to open a file in a text mode ('w'
,'r'
,'wt'
,'rt'
, etc.), it returns a subclass ofio.TextIOBase
(specificallyio.TextIOWrapper
). When used to open a file in a binary mode with buffering, the returned class is a subclass ofio.BufferedIOBase
. The exact class varies: in read binary mode, it returns anio.BufferedReader
; in write binary and append binary modes, it returns anio.BufferedWriter
, and in read/write mode, it returns anio.BufferedRandom
. When buffering is disabled, the raw stream, a subclass ofio.RawIOBase
,io.FileIO
, is returned.另請參閱檔案操作模組,例如
fileinput
、io
(定義了open()
的 module )、os
、os.path
、tempfile
以及shutil
。引發一個附帶引數
file
、model
、flags
的稽核事件open
。The
mode
andflags
arguments may have been modified or inferred from the original call.在 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
.For
int
operands base and exp, if mod is present, mod must also be of integer type and mod must be nonzero. If mod is present and exp is negative, base must be relatively prime to mod. In that case,pow(inv_base, -exp, mod)
is returned, where inv_base is an inverse to base modulo mod.Here's an example of computing an inverse for
38
modulo97
:>>> pow(38, -1, mod=97) 23 >>> 23 * 38 % 97 == 1 True
在 3.8 版的變更: For
int
operands, the three-argument form ofpow
now allows the second argument to be negative, permitting computation of modular inverses.在 3.8 版的變更: Allow keyword arguments. Formerly, only positional arguments were supported.
- print(*objects, sep=' ', end='\n', file=None, flush=False)¶
Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like
str()
does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also beNone
, which means to use the default values. If no objects are given,print()
will just write end.The file argument must be an object with a
write(string)
method; if it is not present orNone
,sys.stdout
will be used. Since printed arguments are converted to text strings,print()
cannot be used with binary mode file objects. For these, usefile.write(...)
instead.Output buffering is usually determined by file. However, if flush is true, the stream is forcibly flushed.
在 3.3 版的變更: 增加了 flush 關鍵字引數。
- class property(fget=None, fset=None, fdel=None, doc=None)¶
回傳 property 屬性。
fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.
A typical use is to define a managed attribute
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.")
If c is an instance of C,
c.x
will invoke the getter,c.x = value
will invoke the setter, anddel c.x
the deleter.If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using
property()
as a decorator:class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
The
@property
decorator turns thevoltage()
method into a "getter" for a read-only attribute with the same name, and it sets the docstring for voltage to "Get the current voltage."- @getter¶
- @setter¶
- @deleter¶
A property object has
getter
,setter
, anddeleter
methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example: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
This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (
x
in this case.)The returned property object also has the attributes
fget
,fset
, andfdel
corresponding to the constructor arguments.
在 3.5 版的變更: The docstrings of property objects are now writeable.
- class range(stop)
- class range(start, stop, step=1)
Rather than being a function,
range
is actually an immutable sequence type, as documented in Ranges and Sequence Types --- list, tuple, range.
- repr(object)¶
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to
eval()
; otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a__repr__()
method. Ifsys.displayhook()
is not accessible, this function will raiseRuntimeError
.
- reversed(seq)¶
Return a reverse iterator. seq 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)¶
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is
None
, it returns the nearest integer to its input.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
,round
delegates tonumber.__round__
.備註
The behavior of
round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead 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
- class set(iterable)
Return a new
set
object, optionally with elements taken from iterable.set
is a built-in class. Seeset
and Set Types --- set, frozenset for documentation about this class.For other containers see the built-in
frozenset
,list
,tuple
, anddict
classes, as well as thecollections
module.
- 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 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
.- start¶
- stop¶
- step¶
Slice objects have read-only data attributes
start
,stop
, andstep
which merely return the argument values (or their default). They have no other explicit functionality; however, they are used by NumPy and other third-party packages.
Slice objects are also generated when extended indexing syntax is used. For example:
a[start:stop:step]
ora[start:stop, i]
. Seeitertools.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 reflected the__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, they can be called as regular functions (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
staticmethod
as 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 methods now inherit the method attributes (
__module__
,__name__
,__qualname__
,__doc__
and__annotations__
), have a new__wrapped__
attribute, and are now callable as regular functions.
- class str(object='')
- class str(object=b'', encoding='utf-8', errors='strict')
Return a
str
version of object. Seestr()
for details.str
is 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 on most builds.
- 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 -> object
and the value of type isB
, thensuper()
searchesC -> A -> object
.The
__mro__
attribute of the 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).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().
- class tuple
- class tuple(iterable)
Rather than being a function,
tuple
is actually an immutable sequence type, as documented in Tuples and Sequence Types --- list, tuple, range.
- class type(object)¶
- class type(name, bases, dict, **kwds)
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
class
statement. 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 identicaltype
objects:>>> class X: ... a = 1 ... >>> X = type('X', (), dict(a=1))
另請參閱 Type Objects。
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
type
which 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.MappingProxyType
to prevent direct dictionary updates).Without an argument,
vars()
acts likelocals()
. Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.A
TypeError
exception is raised if an object is specified but it doesn't have a__dict__
attribute (for example, if its class defines the__slots__
attribute).
- 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 afor
loop 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:By default,
zip()
stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'])) [(0, 'fee'), (1, 'fi'), (2, 'fo')]
zip()
is often used in cases where the iterables are assumed to be of equal length. In such cases, it's recommended to use thestrict=True
option. Its output is the same as regularzip()
:>>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True)) [('a', 1), ('b', 2), ('c', 3)]
Unlike the default behavior, it raises a
ValueError
if one iterable is exhausted before the others:>>> 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
Without the
strict=True
argument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.Shorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by
itertools.zip_longest()
.
Edge cases: With a single iterable argument,
zip()
returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.Tips and tricks:
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n, strict=True)
. This repeats the same iteratorn
times so that each output tuple has the result ofn
calls to the iterator. This has the effect of dividing the input into n-length chunks.zip()
in conjunction with the*
operator can be used to unzip a 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)¶
備註
This is an advanced function that is not needed in everyday Python programming, unlike
importlib.import_module()
.This function is invoked by the
import
statement. It can be replaced (by importing thebuiltins
module and assigning tobuiltins.__import__
) in order to change semantics of theimport
statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of__import__()
is also discouraged in favor ofimportlib.import_module()
.The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all and uses its globals only to determine the package context of the
import
statement.level specifies whether to use absolute or relative imports.
0
(the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling__import__()
(see PEP 328 for the details).When the name variable is of the form
package.module
, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.For example, the statement
import spam
results in bytecode resembling the following code:spam = __import__('spam', globals(), locals(), [], 0)
The statement
import spam.ham
results in this call:spam = __import__('spam.ham', globals(), locals(), [], 0)
Note how
__import__()
returns the toplevel module here because this is the object that is bound to a name by theimport
statement.On the other hand, the statement
from spam.ham import eggs, sausage as saus
results in_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage
Here, the
spam.ham
module is returned from__import__()
. From this object, the names to import are retrieved and assigned to their respective names.If you simply want to import a module (potentially within a package) by name, use
importlib.import_module()
.在 3.3 版的變更: Negative values for level are no longer supported (which also changes the default value to 0).
在 3.9 版的變更: When the command line options
-E
or-I
are being used, the environment variablePYTHONCASEOK
is now ignored.
註解