The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order
Built-in Functions
A
B
C
D
E
F
G
H
I
L
M
N
O
P
R
S
T
V
Z
_
abs[x]Trả về giá trị tuyệt đối của một số. The argument may be an integer, a floating point number, or an object implementing
def any[iterable]: for element in iterable: if element: return True return False05. If the argument is a complex number, its magnitude is returnedaiter[async_iterable]
Trả lại một cho một. Tương đương với việc gọi
def any[iterable]: for element in iterable: if element: return True return False06
Ghi chú. Không giống như , không có biến thể 2 đối số
Mới trong phiên bản 3. 10
tất cả[iterable]Trả về
def any[iterable]: for element in iterable: if element: return True return False09 nếu tất cả các phần tử của iterable là đúng [hoặc nếu iterable trống]. Tương đương với
def all[iterable]: for element in iterable: if not element: return False return Trueawaitable anext[async_iterator]awaitable anext[async_iterator , default]
Khi được chờ đợi, hãy trả về mục tiếp theo từ đã cho hoặc mặc định nếu đã cho và trình vòng lặp đã cạn kiệt
Đây là biến thể không đồng bộ của nội trang và hoạt động tương tự
Điều này gọi phương thức async_iterator, trả về một. Đang chờ điều này trả về giá trị tiếp theo của trình vòng lặp. Nếu giá trị mặc định được đưa ra, nó sẽ được trả về nếu bộ lặp đã cạn kiệt, nếu không thì sẽ được nâng lên
Mới trong phiên bản 3. 10
bất kỳ[iterable]Trả lại
def any[iterable]: for element in iterable: if element: return True return False09 nếu bất kỳ phần tử nào của iterable là true. Nếu iterable trống, hãy trả về
def any[iterable]: for element in iterable: if element: return True return False14. Tương đương với
def any[iterable]: for element in iterable: if element: return True return Falseascii[object]
As , return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by using
def any[iterable]: for element in iterable: if element: return True return False17,
def any[iterable]: for element in iterable: if element: return True return False18, or
def any[iterable]: for element in iterable: if element: return True return False19 escapes. This generates a string similar to that returned by in Python 2bin[x]
Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python object, it has to define an
def any[iterable]: for element in iterable: if element: return True return False22 method that returns an integer. Some examples
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'
If the prefix “0b” is desired or not, you can use either of the following ways
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']
See also for more information
class bool[x=False]Return a Boolean value, i. e. one of
def any[iterable]: for element in iterable: if element: return True return False09 or
def any[iterable]: for element in iterable: if element: return True return False14. x is converted using the standard . If x is false or omitted, this returns
def any[iterable]: for element in iterable: if element: return True return False14; otherwise, it returns
def any[iterable]: for element in iterable: if element: return True return False09. The class is a subclass of [see ]. It cannot be subclassed further. Các phiên bản duy nhất của nó là
def any[iterable]: for element in iterable: if element: return True return False14 và
def any[iterable]: for element in iterable: if element: return True return False09 [xem phần ]
Đã thay đổi trong phiên bản 3. 7. x hiện là tham số chỉ vị trí.
điểm dừng[*args , **kws]Chức năng này đưa bạn vào trình gỡ lỗi tại trang cuộc gọi. Cụ thể, nó gọi , chuyển thẳng
def any[iterable]: for element in iterable: if element: return True return False33 và
def any[iterable]: for element in iterable: if element: return True return False34. Theo mặc định, các cuộc gọi
def any[iterable]: for element in iterable: if element: return True return False32 không mong đợi đối số. Trong trường hợp này, nó hoàn toàn là một chức năng tiện lợi, do đó bạn không cần phải nhập hoặc nhập nhiều mã một cách rõ ràng để vào trình gỡ lỗi. Tuy nhiên, có thể được đặt thành một số chức năng khác và sẽ tự động gọi chức năng đó, cho phép bạn đưa vào trình gỡ lỗi đã chọn. Nếu không truy cập được, chức năng này sẽ tăng
Đưa ra một
def any[iterable]: for element in iterable: if element: return True return False42 với đối số
def any[iterable]: for element in iterable: if element: return True return False43
Mới trong phiên bản 3. 7
lớp bytearray[source=b'']class bytearray[source , encoding]class bytearray[source , encoding , errors]Trả về một mảng byte mới. Lớp là một dãy số nguyên có thể thay đổi trong phạm vi 0 >> bin[3] '0b11' >>> bin[-10] '-0b1010' 00 với các đối số
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'01 và
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'02. Sự kiện này cũng có thể được nâng lên bằng cách tổng hợp ngầm
Ghi chú
Khi biên dịch một chuỗi có mã nhiều dòng ở chế độ
def any[iterable]: for element in iterable: if element: return True return False82 hoặc
def any[iterable]: for element in iterable: if element: return True return False81, đầu vào phải được kết thúc bằng ít nhất một ký tự dòng mới. Điều này là để tạo điều kiện phát hiện các báo cáo không đầy đủ và đầy đủ trong mô-đun
Cảnh báo
Có thể làm hỏng trình thông dịch Python với chuỗi đủ lớn/phức tạp khi biên dịch thành đối tượng AST do giới hạn độ sâu ngăn xếp trong trình biên dịch AST của Python
Đã thay đổi trong phiên bản 3. 2. Được phép sử dụng dòng mới của Windows và Mac. Ngoài ra, đầu vào ở chế độ
def any[iterable]: for element in iterable: if element: return True return False80 không phải kết thúc bằng một dòng mới nữa. Đã thêm tham số tối ưu hóa.
Đã thay đổi trong phiên bản 3. 5. Previously, was raised when null bytes were encountered in source.
Mới trong phiên bản 3. 8. _______11_______08 giờ đây có thể được chuyển vào cờ để cho phép hỗ trợ cho cấp cao nhất
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'09,
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'10 và
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'11. lớp complex[real=0 , imag=0]class complex[string]
Trả về một số phức với giá trị thực + hình ảnh*1j hoặc chuyển đổi một chuỗi hoặc số thành một số phức. Nếu tham số đầu tiên là một chuỗi, nó sẽ được hiểu là một số phức và hàm phải được gọi mà không có tham số thứ hai. Tham số thứ hai không bao giờ có thể là một chuỗi. Mỗi đối số có thể là bất kỳ loại số nào [kể cả phức tạp]. Nếu hình ảnh bị bỏ qua, nó sẽ mặc định bằng 0 và hàm tạo đóng vai trò chuyển đổi số như và. Nếu cả hai đối số bị bỏ qua, trả về
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'14
Đối với một đối tượng Python chung
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'15,
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'16 ủy quyền cho
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'17. Nếu
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'18 không được xác định thì nó sẽ quay trở lại
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'19. Nếu
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'19 không được xác định thì nó sẽ quay trở lại
def any[iterable]: for element in iterable: if element: return True return False22
Ghi chú
Khi chuyển đổi từ một chuỗi, chuỗi không được chứa khoảng trắng xung quanh toán tử trung tâm
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'22 hoặc
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'23. Ví dụ:
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'24 thì được, nhưng
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'25 tăng
Loại phức tạp được mô tả trong
Đã thay đổi trong phiên bản 3. 6. Cho phép nhóm các chữ số có dấu gạch dưới như trong mã chữ.
Đã thay đổi trong phiên bản 3. 8. Trở về
def any[iterable]: for element in iterable: if element: return True return False22 nếu
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'18 và
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'19 không được xác định. delattr[object , name]
Đây là họ hàng của. Các đối số là một đối tượng và một chuỗi. Chuỗi phải là tên của một trong các thuộc tính của đối tượng. Hàm xóa thuộc tính được đặt tên, miễn là đối tượng cho phép. Ví dụ,
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'31 tương đương với
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'32. tên không cần phải là mã định danh Python [xem ]class dict[**kwarg]class dict[mapping , **kwarg]class dict[iterable , **kwarg]
Tạo từ điển mới. Đối tượng là lớp từ điển. Xem và để biết tài liệu về lớp học này
Đối với các vùng chứa khác, hãy xem các lớp , và lớp tích hợp cũng như mô-đun
dir[]dir[object]Không có đối số, trả về danh sách tên trong phạm vi cục bộ hiện tại. Với một đối số, cố gắng trả về danh sách các thuộc tính hợp lệ cho đối tượng đó
Nếu đối tượng có một phương thức tên là
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'40, thì phương thức này sẽ được gọi và phải trả về danh sách các thuộc tính. Điều này cho phép các đối tượng triển khai hàm
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'41 hoặc
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'42 tùy chỉnh để tùy chỉnh cách báo cáo các thuộc tính của chúng
Nếu đối tượng không cung cấp
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'40, hàm sẽ cố gắng hết sức để thu thập thông tin từ thuộc tính của đối tượng, nếu được xác định và từ đối tượng loại của nó. Danh sách kết quả không nhất thiết phải đầy đủ và có thể không chính xác khi đối tượng có tùy chỉnh
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'41
Cơ chế mặc định hoạt động khác với các loại đối tượng khác nhau, vì nó cố gắng tạo ra thông tin phù hợp nhất, thay vì thông tin đầy đủ
Nếu đối tượng là một đối tượng mô-đun, danh sách chứa tên của các thuộc tính của mô-đun
Nếu đối tượng là một đối tượng kiểu hoặc lớp, thì danh sách chứa tên của các thuộc tính của nó và đệ quy các thuộc tính của các cơ sở của nó
Mặt khác, danh sách chứa các tên thuộc tính của đối tượng, tên của các thuộc tính của lớp đối tượng và đệ quy các thuộc tính của các lớp cơ sở của lớp đối tượng.
Danh sách kết quả được sắp xếp theo thứ tự bảng chữ cái. Ví dụ
>>> 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']
Ghi chú
Do được cung cấp chủ yếu để thuận tiện cho việc sử dụng tại một dấu nhắc tương tác, nó cố gắng cung cấp một bộ tên thú vị hơn là cố gắng cung cấp một bộ tên được xác định chặt chẽ hoặc nhất quán và hành vi chi tiết của nó có thể thay đổi qua các bản phát hành. For example, metaclass attributes are not in the result list when the argument is a class
divmod[a , b]Take two [non-complex] numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'49. For floating point numbers the result is
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'50, where q is usually
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'51 but may be 1 less than that. In any case
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'52 is very close to a, if
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'53 is non-zero it has the same sign as b, and
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'54enumerate[iterable , start=0]
Return an enumerate object. iterable must be a sequence, an , or some other object which supports iteration. The method of the iterator returned by returns a tuple containing a count [from start which defaults to 0] and the values obtained from iterating over 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']]
Equivalent to
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 1eval[expression , globals=None , locals=None]
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object
The expression argument is parsed and evaluated as a Python expression [technically speaking, a condition list] using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'57, a reference to the dictionary of the built-in module 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
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'57 dictionary into globals before passing it to . If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where is called. Note, eval[] does not have access to the [non-locals] in the enclosing environment
The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example
>>> x = 1 >>> eval['x+1'] 2
This function can also be used to execute arbitrary code objects [such as those created by ]. In this case, pass a code object instead of a string. If the code object has been compiled with
def any[iterable]: for element in iterable: if element: return True return False80 as the mode argument, 's return value will be
def any[iterable]: for element in iterable: if element: return True return False83
Hints. dynamic execution of statements is supported by the function. The and functions return the current global and local dictionary, respectively, which may be useful to pass around for use by or
If the given source is a string, then leading and trailing spaces and tabs are stripped
See for a function that can safely evaluate strings with expressions containing only literals
Raises an
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'72 with the code object as the argument. Code compilation events may also be raisedexec[object , globals=None , locals=None , / , * , closure=None]
This function supports dynamic execution of Python code. object 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]. 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 , , and statements may not be used outside of function definitions even within the context of code passed to the function. The return value is
def any[iterable]: for element in iterable: if element: return True return False83
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. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition
If the globals dictionary does not contain a value for the key
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'57, a reference to the dictionary of the built-in module is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'57 dictionary into globals before passing it to
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
Raises an
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'72 with the code object as the argument. Code compilation events may also be raised
Ghi chú
The built-in functions and return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to
Ghi chú
The default locals act as described for function below. modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function returns
Changed in version 3. 11. Added the closure parameter.
filter[function , iterable]Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is
def any[iterable]: for element in iterable: if element: return True return False83, the identity function is assumed, that is, all elements of iterable that are false are removed
Note that
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'89 is equivalent to the generator expression
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'90 if function is not
def any[iterable]: for element in iterable: if element: return True return False83 and
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'92 if function is
def any[iterable]: for element in iterable: if element: return True return False83
See for the complementary function that returns elements of iterable for which function returns false
class float[x=0. 0]Return a floating point number constructed from a number or string x
If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'95 or
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'96; a
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'95 sign has no effect on the value produced. The argument may also be a string representing a NaN [not-a-number], or positive or negative infinity. More precisely, the input must conform to the
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'98 production rule in the following grammar, after leading and trailing whitespace characters are removed
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
]
Here
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'99 is a Unicode decimal digit [character in the Unicode general category
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']00]. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY”, and “iNfINity” are all acceptable spellings for positive infinity
Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value [within Python’s floating point precision] is returned. If the argument is outside the range of a Python float, an will be raised
For a general Python object
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'15,
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']03 delegates to
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']04. If
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'19 is not defined then it falls back to
def any[iterable]: for element in iterable: if element: return True return False22
If no argument is given,
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']07 is returned
Examples
def any[iterable]: for element in iterable: if element: return True return False0
The float type is described in
Đã thay đổi trong phiên bản 3. 6. Cho phép nhóm các chữ số có dấu gạch dưới như trong mã chữ.
Đã thay đổi trong phiên bản 3. 7. x hiện là tham số chỉ vị trí.
Changed in version 3. 8. Falls back to
def any[iterable]: for element in iterable: if element: return True return False22 if
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'19 is not defined. format[value , format_spec='']
Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types.
The default format_spec is an empty string which usually gives the same effect as calling
A call to
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']11 is translated to
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']12 which bypasses the instance dictionary when searching for the value’s
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']13 method. A exception is raised if the method search reaches and the format_spec is non-empty, or if either the format_spec or the return value are not strings
Changed in version 3. 4.
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']16 raises if format_spec is not an empty string. class frozenset[iterable=set[]]
Return a new object, optionally with elements taken from iterable.
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']18 is a built-in class. See and for documentation about this class
For other containers see the built-in , , , and classes, as well as the module
getattr[object , name]getattr[object , name , default]Return the value of the named attribute of object. name must be a string. Nếu chuỗi là tên của một trong các thuộc tính của đối tượng, thì kết quả là giá trị của thuộc tính đó. Ví dụ,
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']26 tương đương với
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']27. Nếu thuộc tính được đặt tên không tồn tại, giá trị mặc định sẽ được trả về nếu được cung cấp, nếu không thì sẽ được nâng lên. name need not be a Python identifier [see ]
Ghi chú
Since happens at compilation time, one must manually mangle a private attribute’s [attributes with two leading underscores] name in order to retrieve it with
globals[]Return the dictionary implementing the current module namespace. Đối với mã bên trong hàm, giá trị này được đặt khi hàm được xác định và giữ nguyên bất kể hàm được gọi ở đâu
hasattr[object , name]The arguments are an object and a string. Kết quả là
def any[iterable]: for element in iterable: if element: return True return False09 nếu chuỗi là tên của một trong các thuộc tính của đối tượng,
def any[iterable]: for element in iterable: if element: return True return False14 nếu không. [This is implemented by calling
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']33 and seeing whether it raises an or not. ]hash[object]
Trả về giá trị băm của đối tượng [nếu có]. Giá trị băm là số nguyên. Chúng được sử dụng để so sánh nhanh các khóa từ điển trong quá trình tra cứu từ điển. Các giá trị số so sánh bằng nhau có cùng giá trị băm [ngay cả khi chúng thuộc các loại khác nhau, như trường hợp của 1 và 1. 0]
Ghi chú
Đối với các đối tượng có phương thức
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']35 tùy chỉnh, hãy lưu ý rằng việc cắt bớt giá trị trả về dựa trên độ rộng bit của máy chủ. Xem
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']35 để biết chi tiếthelp[]help[request]
Invoke the built-in help system. [This function is intended for interactive use. ] Nếu không có đối số nào được đưa ra, hệ thống trợ giúp tương tác sẽ bắt đầu trên bảng điều khiển phiên dịch. Nếu đối số là một chuỗi, thì chuỗi đó được tra cứu dưới dạng tên của mô-đun, hàm, lớp, phương thức, từ khóa hoặc chủ đề tài liệu và trang trợ giúp được in trên bảng điều khiển. Nếu đối số là bất kỳ loại đối tượng nào khác, một trang trợ giúp về đối tượng sẽ được tạo
Lưu ý rằng nếu dấu gạch chéo [/] xuất hiện trong danh sách tham số của hàm khi gọi , điều đó có nghĩa là các tham số trước dấu gạch chéo chỉ là vị trí. Để biết thêm thông tin, xem
Chức năng này được mô-đun thêm vào không gian tên tích hợp
Changed in version 3. 4. Thay đổi và có nghĩa là chữ ký được báo cáo cho các cuộc gọi hiện toàn diện và nhất quán hơn.
hex[x]Chuyển đổi một số nguyên thành chuỗi thập lục phân chữ thường có tiền tố là “0x”. Nếu x không phải là một đối tượng Python, thì nó phải định nghĩa một phương thức
def any[iterable]: for element in iterable: if element: return True return False22 trả về một số nguyên. Vài ví dụ
def any[iterable]: for element in iterable: if element: return True return False1
Nếu bạn muốn chuyển đổi một số nguyên sang một chuỗi thập lục phân hoa hoặc thường có tiền tố hoặc không, bạn có thể sử dụng một trong hai cách sau
def any[iterable]: for element in iterable: if element: return True return False2
See also for more information
Xem thêm để chuyển đổi chuỗi thập lục phân thành số nguyên bằng cách sử dụng cơ số 16
Ghi chú
To obtain a hexadecimal string representation for a float, use the method
id[object]Trả về “danh tính” của một đối tượng. Đây là một số nguyên được đảm bảo là duy nhất và không đổi cho đối tượng này trong suốt thời gian tồn tại của nó. Hai đối tượng có thời gian sống không chồng lấp có thể có cùng giá trị
Chi tiết triển khai CPython. Đây là địa chỉ của đối tượng trong bộ nhớ
Đưa ra một
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']48 với lập luận
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']49đầu vào[]input[prompt]
Nếu có đối số dấu nhắc, nó sẽ được ghi vào đầu ra tiêu chuẩn mà không có dòng mới ở cuối. Sau đó, hàm đọc một dòng từ đầu vào, chuyển đổi nó thành một chuỗi [bỏ một dòng mới ở cuối] và trả về dòng đó. Khi EOF được đọc, được nâng lên. Thí dụ
def any[iterable]: for element in iterable: if element: return True return False3
Nếu mô-đun đã được tải, thì sẽ sử dụng mô-đun đó để cung cấp các tính năng lịch sử và chỉnh sửa dòng phức tạp
Tăng một
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']53 với đối số
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']54 trước khi đọc đầu vào
Tăng một
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']55 với kết quả sau khi đọc thành công đầu vàoclass int[x=0]class int[x , base=10]
Trả về một đối tượng số nguyên được tạo từ một số hoặc chuỗi x hoặc trả về
def any[iterable]: for element in iterable: if element: return True return False92 nếu không có đối số nào được đưa ra. Nếu x xác định
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']57,
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']58 trả về
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']59. Nếu x định nghĩa
def any[iterable]: for element in iterable: if element: return True return False22, nó trả về
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']61. Nếu x định nghĩa
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']62, nó trả về
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']63. Đối với các số dấu phẩy động, số này cắt ngắn về 0
Nếu x không phải là một số hoặc nếu cơ số được đưa ra, thì x phải là một chuỗi, , hoặc thể hiện đại diện cho một số nguyên trong cơ số. Theo tùy chọn, chuỗi có thể được bắt đầu bằng
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'22 hoặc
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'23 [không có khoảng trắng ở giữa], có các số 0 ở đầu, được bao quanh bởi khoảng trắng và có một dấu gạch dưới nằm xen kẽ giữa các chữ số
Một chuỗi số nguyên cơ sở n chứa các chữ số, mỗi chữ số đại diện cho một giá trị từ 0 đến n-1. Các giá trị 0–9 có thể được biểu thị bằng bất kỳ chữ số thập phân Unicode nào. Các giá trị 10–35 có thể được biểu thị bằng
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']68 đến
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']69 [hoặc
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']70 đến
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']71]. Cơ sở mặc định là 10. Các cơ số được phép là 0 và 2–36. Các chuỗi cơ sở 2, -8 và -16 có thể được thêm tiền tố tùy chọn bằng
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']72/
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']73,
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']74/
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']75 hoặc
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']76/
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']77, như với các ký tự số nguyên trong mã. Đối với cơ số 0, chuỗi được diễn giải theo cách tương tự với một , trong đó cơ số thực tế là 2, 8, 10 hoặc 16 như được xác định bởi tiền tố. Cơ sở 0 cũng không cho phép các số 0 đứng đầu.
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']78 là không hợp pháp, trong khi
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']79 và
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']80 là
Kiểu số nguyên được mô tả trong
Changed in version 3. 4. Nếu cơ sở không phải là một thể hiện của đối tượng cơ sở và đối tượng cơ sở có một phương thức, thì phương thức đó được gọi để lấy một số nguyên cho cơ sở. Các phiên bản trước được sử dụng thay vì.
Đã thay đổi trong phiên bản 3. 6. Cho phép nhóm các chữ số có dấu gạch dưới như trong mã chữ.
Đã thay đổi trong phiên bản 3. 7. x hiện là tham số chỉ vị trí.
Đã thay đổi trong phiên bản 3. 8. Trở về
def any[iterable]: for element in iterable: if element: return True return False22 nếu không xác định được
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']57.
Đã thay đổi trong phiên bản 3. 11. Việc ủy quyền cho
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']62 không được chấp nhận.
Đã thay đổi trong phiên bản 3. 11. đầu vào chuỗi và biểu diễn chuỗi có thể bị giới hạn để giúp tránh các cuộc tấn công từ chối dịch vụ. A được nâng lên khi vượt quá giới hạn trong khi chuyển đổi chuỗi x thành chuỗi hoặc khi chuyển đổi chuỗi thành chuỗi sẽ vượt quá giới hạn. See the documentation.
isinstance[object , classinfo]Trả về
def any[iterable]: for element in iterable: if element: return True return False09 nếu đối số đối tượng là một thể hiện của đối số classinfo hoặc của một lớp con [trực tiếp, gián tiếp hoặc ] của nó. If object is not an object of the given type, the function always returns
def any[iterable]: for element in iterable: if element: return True return False14. Nếu classinfo là một bộ gồm các đối tượng loại [hoặc theo cách đệ quy, các bộ khác như vậy] hoặc một thuộc nhiều loại, hãy trả về
def any[iterable]: for element in iterable: if element: return True return False09 nếu đối tượng là một thể hiện của bất kỳ loại nào. Nếu classinfo không phải là một loại hoặc bộ dữ liệu của các loại và các bộ dữ liệu như vậy, một ngoại lệ sẽ được đưa ra. có thể không được nâng lên đối với loại không hợp lệ nếu kiểm tra trước đó thành công
Đã thay đổi trong phiên bản 3. 10. classinfo có thể là một.
issubclass[class , classinfo]Trả về
def any[iterable]: for element in iterable: if element: return True return False09 nếu lớp là lớp con [trực tiếp, gián tiếp hoặc ] của classinfo. Một lớp được coi là một lớp con của chính nó. classinfo có thể là một bộ của các đối tượng lớp [hoặc đệ quy, các bộ khác như vậy] hoặc một , trong trường hợp đó trả về
def any[iterable]: for element in iterable: if element: return True return False09 nếu lớp là một lớp con của bất kỳ mục nào trong classinfo. Trong mọi trường hợp khác, một ngoại lệ được nêu ra
Đã thay đổi trong phiên bản 3. 10. classinfo có thể là một.
iter[object]iter[object , sentinel]Trả lại một đối tượng. Đối số đầu tiên được diễn giải rất khác nhau tùy thuộc vào sự hiện diện của đối số thứ hai. Không có đối số thứ hai, đối tượng phải là một đối tượng tập hợp hỗ trợ giao thức [phương thức
class C: @classmethod def f[cls, arg1, arg2]: ...00] hoặc nó phải hỗ trợ giao thức trình tự [phương thức
class C: @classmethod def f[cls, arg1, arg2]: ...01 với các đối số số nguyên bắt đầu từ
def any[iterable]: for element in iterable: if element: return True return False92]. Nếu nó không hỗ trợ một trong hai giao thức đó, nó sẽ được nâng lên. Nếu đối số thứ hai, sentinel, được đưa ra, thì đối tượng phải là đối tượng có thể gọi được. Trình lặp được tạo trong trường hợp này sẽ gọi đối tượng không có đối số cho mỗi lệnh gọi đến phương thức của nó;
Xem thêm
Một ứng dụng hữu ích của dạng thứ hai là xây dựng trình đọc khối. Ví dụ: đọc các khối có chiều rộng cố định từ tệp cơ sở dữ liệu nhị phân cho đến khi đạt đến cuối tệp
def any[iterable]: for element in iterable: if element: return True return False4len[s]
Trả về chiều dài [số lượng mục] của một đối tượng. Đối số có thể là một chuỗi [chẳng hạn như chuỗi, byte, bộ, danh sách hoặc phạm vi] hoặc bộ sưu tập [chẳng hạn như từ điển, tập hợp hoặc tập hợp cố định]
Chi tiết triển khai CPython.
class C: @classmethod def f[cls, arg1, arg2]: ...07 tăng trên chiều dài lớn hơn , chẳng hạn nhưlớp listclass list[iterable]
Thay vì là một chức năng, thực sự là một loại trình tự có thể thay đổi, như được ghi lại trong và
người dân địa phương[]Cập nhật và trả về một từ điển đại diện cho bảng ký hiệu cục bộ hiện tại. Các biến miễn phí được trả về khi nó được gọi trong các khối chức năng, nhưng không phải trong các khối lớp. Lưu ý rằng ở cấp độ mô-đun và từ điển giống nhau
Ghi chú
Nội dung của từ điển này không nên được sửa đổi;
map[function , iterable , *iterables]Trả về một trình vòng lặp áp dụng hàm cho mọi mục có thể lặp lại, mang lại kết quả. Nếu các đối số lặp bổ sung được truyền, hàm phải nhận nhiều đối số đó và được áp dụng song song cho các mục từ tất cả các lần lặp. Với nhiều lần lặp, trình lặp dừng khi hết lần lặp ngắn nhất. Đối với các trường hợp đầu vào hàm đã được sắp xếp thành các bộ đối số, hãy xem
tối đa[iterable , * , key=None]max[iterable , * , default , key=None]max[arg1 , arg2 , *args , key=None]Trả về mục lớn nhất trong một lần lặp hoặc mục lớn nhất trong hai hoặc nhiều đối số
Nếu một đối số vị trí được cung cấp, nó phải là một. Mục lớn nhất trong iterable được trả về. Nếu hai hoặc nhiều đối số vị trí được cung cấp, đối số vị trí lớn nhất được trả về
Có hai đối số chỉ từ khóa tùy chọn. Đối số key chỉ định hàm sắp xếp một đối số như được sử dụng cho. Đối số mặc định chỉ định một đối tượng sẽ trả về nếu iterable được cung cấp trống. Nếu iterable trống và mặc định không được cung cấp, a sẽ tăng
Nếu nhiều mục là tối đa, hàm trả về mục đầu tiên gặp phải. Điều này nhất quán với các công cụ duy trì tính ổn định sắp xếp khác như
class C: @classmethod def f[cls, arg1, arg2]: ...18 và
class C: @classmethod def f[cls, arg1, arg2]: ...19
Mới trong phiên bản 3. 4. Đối số chỉ từ khóa mặc định.
Đã thay đổi trong phiên bản 3. 8. Khóa có thể là
def any[iterable]: for element in iterable: if element: return True return False83. lớp memoryview[object]
Trả về đối tượng "chế độ xem bộ nhớ" được tạo từ đối số đã cho. Xem để biết thêm thông tin
phút[iterable , * , key=None]min[iterable , * , default , phím=None]min[arg1 , arg2 , *args , key=None]Trả về mục nhỏ nhất trong một lần lặp hoặc mục nhỏ nhất trong hai hoặc nhiều đối số
Nếu một đối số vị trí được cung cấp, nó phải là một. Mục nhỏ nhất trong iterable được trả về. Nếu hai hoặc nhiều đối số vị trí được cung cấp, đối số vị trí nhỏ nhất được trả về
Có hai đối số chỉ từ khóa tùy chọn. Đối số key chỉ định hàm sắp xếp một đối số như được sử dụng cho. Đối số mặc định chỉ định một đối tượng sẽ trả về nếu iterable được cung cấp trống. Nếu iterable trống và mặc định không được cung cấp, a sẽ tăng
Nếu nhiều mục là tối thiểu, hàm trả về mục đầu tiên gặp phải. Điều này phù hợp với các công cụ duy trì tính ổn định sắp xếp khác như
class C: @classmethod def f[cls, arg1, arg2]: ...23 và
class C: @classmethod def f[cls, arg1, arg2]: ...24
Mới trong phiên bản 3. 4. Đối số chỉ từ khóa mặc định.
Đã thay đổi trong phiên bản 3. 8. Khóa có thể là
def any[iterable]: for element in iterable: if element: return True return False83. tiếp theo[iterator]next[iterator , default]
Truy xuất mục tiếp theo từ bằng cách gọi phương thức của nó. Nếu giá trị mặc định được đưa ra, nó sẽ được trả về nếu bộ lặp đã cạn kiệt, nếu không thì sẽ được nâng lên
lớp objectTrả lại một đối tượng đặc biệt mới. là cơ sở cho tất cả các lớp. Nó có các phương thức phổ biến cho tất cả các phiên bản của các lớp Python. Chức năng này không chấp nhận bất kỳ đối số
Ghi chú
không có a , vì vậy bạn không thể gán các thuộc tính tùy ý cho một thể hiện của lớp
oct[x]Chuyển đổi một số nguyên thành một chuỗi bát phân có tiền tố là “0o”. Kết quả là một biểu thức Python hợp lệ. Nếu x không phải là một đối tượng Python, thì nó phải định nghĩa một phương thức
def any[iterable]: for element in iterable: if element: return True return False22 trả về một số nguyên. Ví dụ
def any[iterable]: for element in iterable: if element: return True return False5
Nếu bạn muốn chuyển đổi một số nguyên thành một chuỗi bát phân có tiền tố “0o” hoặc không, bạn có thể sử dụng một trong hai cách sau
def any[iterable]: for element in iterable: if element: return True return False6
See also for more information
mở[file , mode='r' , buffering=- 1 , encoding=None , errors=None , newline=None , closefd=True , opener=None]
Mở tệp và trả về một tệp tương ứng. Nếu tệp không thể mở được, một dấu hiệu sẽ xuất hiện. Xem thêm ví dụ về cách sử dụng chức năng này
tệp là cung cấp tên đường dẫn [tuyệt đối hoặc tương đối với thư mục làm việc hiện tại] của tệp sẽ được mở hoặc một bộ mô tả tệp số nguyên của tệp sẽ được gói. [Nếu một bộ mô tả tệp được cung cấp, nó sẽ bị đóng khi đối tượng I/O được trả về bị đóng trừ khi closefd được đặt thành
def any[iterable]: for element in iterable: if element: return True return False14. ]
chế độ là một chuỗi tùy chọn chỉ định chế độ mở tệp. Nó mặc định là
class C: @classmethod def f[cls, arg1, arg2]: ...37 có nghĩa là mở để đọc ở chế độ văn bản. Các giá trị phổ biến khác là
class C: @classmethod def f[cls, arg1, arg2]: ...38 để ghi [cắt bớt tệp nếu nó đã tồn tại],
class C: @classmethod def f[cls, arg1, arg2]: ...39 để tạo độc quyền và
def any[iterable]: for element in iterable: if element: return True return False59 để nối thêm [trên một số hệ thống Unix, có nghĩa là tất cả các ghi sẽ nối vào cuối tệp bất kể vị trí tìm kiếm hiện tại . Ở chế độ văn bản, nếu mã hóa không được chỉ định thì mã hóa được sử dụng phụ thuộc vào nền tảng. được gọi để lấy mã hóa ngôn ngữ hiện tại. [Để đọc và ghi byte thô, hãy sử dụng chế độ nhị phân và để mã hóa không xác định. ] Các chế độ khả dụng là
Nhân vật
Nghĩa
class C: @classmethod def f[cls, arg1, arg2]: ...37
mở để đọc [mặc định]
class C: @classmethod def f[cls, arg1, arg2]: ...38
mở để viết, cắt bớt tệp trước
class C: @classmethod def f[cls, arg1, arg2]: ...39
mở để tạo độc quyền, không thành công nếu tệp đã tồn tại
def any[iterable]: for element in iterable: if element: return True return False59
mở để viết, thêm vào cuối tệp nếu nó tồn tại
class C: @classmethod def f[cls, arg1, arg2]: ...46
chế độ nhị phân
class C: @classmethod def f[cls, arg1, arg2]: ...47
chế độ văn bản [mặc định]
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'95
mở để cập nhật [đọc và viết]
Chế độ mặc định là
class C: @classmethod def f[cls, arg1, arg2]: ...37 [mở để đọc văn bản, đồng nghĩa với
class C: @classmethod def f[cls, arg1, arg2]: ...50]. Chế độ
class C: @classmethod def f[cls, arg1, arg2]: ...51 và
class C: @classmethod def f[cls, arg1, arg2]: ...52 mở và cắt bớt tệp. Chế độ
class C: @classmethod def f[cls, arg1, arg2]: ...53 và
class C: @classmethod def f[cls, arg1, arg2]: ...54 mở tệp mà không cắt bớt
Như đã đề cập trong phần , Python phân biệt giữa I/O nhị phân và văn bản. Các tệp được mở ở chế độ nhị phân [bao gồm
class C: @classmethod def f[cls, arg1, arg2]: ...46 trong đối số chế độ] trả về nội dung dưới dạng đối tượng mà không cần giải mã. Ở chế độ văn bản [mặc định hoặc khi
class C: @classmethod def f[cls, arg1, arg2]: ...47 được bao gồm trong đối số chế độ], nội dung của tệp được trả về dưới dạng , các byte đã được giải mã lần đầu bằng mã hóa phụ thuộc vào nền tảng hoặc sử dụng mã hóa được chỉ định nếu được cung cấp
Ghi chú
Python không phụ thuộc vào khái niệm tệp văn bản của hệ điều hành cơ bản;
đệm là một số nguyên tùy chọn được sử dụng để đặt chính sách đệm. Vượt qua 0 để tắt bộ đệm [chỉ được phép ở chế độ nhị phân], 1 để chọn bộ đệm dòng [chỉ có thể sử dụng ở chế độ văn bản] và một số nguyên > 1 để biểu thị kích thước tính bằng byte của bộ đệm khối có kích thước cố định. Lưu ý rằng việc chỉ định kích thước bộ đệm theo cách này áp dụng cho I/O được đệm nhị phân, nhưng
class C: @classmethod def f[cls, arg1, arg2]: ...59 [i. e. , các tệp được mở bằng
class C: @classmethod def f[cls, arg1, arg2]: ...60] sẽ có một bộ đệm khác. Để vô hiệu hóa bộ đệm trong
class C: @classmethod def f[cls, arg1, arg2]: ...59, hãy cân nhắc sử dụng cờ
class C: @classmethod def f[cls, arg1, arg2]: ...62 cho. Khi không đưa ra đối số đệm, chính sách đệm mặc định hoạt động như sau
Các tệp nhị phân được đệm trong các khối có kích thước cố định; . Trên nhiều hệ thống, bộ đệm thường dài 4096 hoặc 8192 byte
Tệp văn bản “tương tác” [tệp trả về ____0_______09] sử dụng bộ đệm dòng. Các tệp văn bản khác sử dụng chính sách được mô tả ở trên cho các tệp nhị phân
mã hóa là tên của mã hóa được sử dụng để giải mã hoặc mã hóa tệp. Điều này chỉ nên được sử dụng trong chế độ văn bản. Mã hóa mặc định phụ thuộc vào nền tảng [bất kỳ thứ gì trả về], nhưng bất kỳ thứ gì được Python hỗ trợ đều có thể được sử dụng. Xem mô-đun để biết danh sách mã hóa được hỗ trợ
lỗi là một chuỗi tùy chọn chỉ định cách xử lý lỗi mã hóa và giải mã—không thể sử dụng chuỗi này ở chế độ nhị phân. Có sẵn nhiều trình xử lý lỗi tiêu chuẩn [được liệt kê bên dưới], mặc dù bất kỳ tên xử lý lỗi nào đã được đăng ký cũng hợp lệ. Tên tiêu chuẩn bao gồm
class C: @classmethod def f[cls, arg1, arg2]: ...
70 để đưa ra ngoại lệ nếu có lỗi mã hóa. Giá trị mặc định củadef any[iterable]: for element in iterable: if element: return True return False
83 có tác dụng tương tựclass C: @classmethod def f[cls, arg1, arg2]: ...
73 bỏ qua lỗi. Lưu ý rằng bỏ qua lỗi mã hóa có thể dẫn đến mất dữ liệuclass C: @classmethod def f[cls, arg1, arg2]: ...
74 khiến một điểm đánh dấu thay thế [chẳng hạn nhưclass C: @classmethod def f[cls, arg1, arg2]: ...
75] được chèn vào nơi có dữ liệu không đúng định dạngclass C: @classmethod def f[cls, arg1, arg2]: ...
76 sẽ đại diện cho bất kỳ byte không chính xác nào dưới dạng đơn vị mã thay thế thấp, từ U+DC80 đến U+DCFF. Các đơn vị mã thay thế này sau đó sẽ được chuyển trở lại thành các byte giống nhau khi trình xử lý lỗiclass C: @classmethod def f[cls, arg1, arg2]: ...
77 được sử dụng khi ghi dữ liệu. Điều này hữu ích để xử lý các tệp ở dạng mã hóa không xác địnhclass C: @classmethod def f[cls, arg1, arg2]: ...
78 chỉ được hỗ trợ khi ghi vào tệp. Các ký tự không được mã hóa hỗ trợ được thay thế bằng tham chiếu ký tự XML thích hợpclass C: @classmethod def f[cls, arg1, arg2]: ...
79________33 _______80 thay thế dữ liệu không đúng định dạng bằng chuỗi thoát dấu gạch chéo ngược Python
class C: @classmethod def f[cls, arg1, arg2]: ...
81 [cũng chỉ được hỗ trợ khi viết] thay thế các ký tự không được hỗ trợ bằng chuỗi ký tự thoátclass C: @classmethod def f[cls, arg1, arg2]: ...
82
dòng mới xác định cách phân tích các ký tự dòng mới từ luồng. Nó có thể là
def any[iterable]: for element in iterable: if element: return True return False83,
class C: @classmethod def f[cls, arg1, arg2]: ...84,
class C: @classmethod def f[cls, arg1, arg2]: ...85,
class C: @classmethod def f[cls, arg1, arg2]: ...86, và
class C: @classmethod def f[cls, arg1, arg2]: ...87. Nó hoạt động như sau
Khi đọc đầu vào từ luồng, nếu dòng mới là
def any[iterable]: for element in iterable: if element: return True return False
83, chế độ dòng mới chung được bật. Các dòng trong đầu vào có thể kết thúc bằngclass C: @classmethod def f[cls, arg1, arg2]: ...
85,class C: @classmethod def f[cls, arg1, arg2]: ...
86 hoặcclass C: @classmethod def f[cls, arg1, arg2]: ...
87 và những dòng này được dịch thànhclass C: @classmethod def f[cls, arg1, arg2]: ...
85 trước khi được trả lại cho người gọi. If it isclass C: @classmethod def f[cls, arg1, arg2]: ...
84, universal newlines mode is enabled, but line endings are returned to the caller untranslated. Nếu nó có bất kỳ giá trị pháp lý nào khác, các dòng đầu vào chỉ được kết thúc bởi chuỗi đã cho và kết thúc dòng được trả về cho người gọi chưa được dịchKhi ghi đầu ra vào luồng, nếu dòng mới là
def any[iterable]: for element in iterable: if element: return True return False
83, thì bất kỳ ký tựclass C: @classmethod def f[cls, arg1, arg2]: ...
85 nào được ghi sẽ được dịch sang dấu phân cách dòng mặc định của hệ thống,. Nếu dòng mới làclass C: @classmethod def f[cls, arg1, arg2]: ...
84 hoặcclass C: @classmethod def f[cls, arg1, arg2]: ...
85, không có bản dịch nào diễn ra. Nếu dòng mới là bất kỳ giá trị pháp lý nào khác, bất kỳ ký tựclass C: @classmethod def f[cls, arg1, arg2]: ...
85 nào được viết sẽ được dịch sang chuỗi đã cho
Nếu closefd là
def any[iterable]: for element in iterable: if element: return True return False14 và một bộ mô tả tệp chứ không phải tên tệp đã được cung cấp, thì bộ mô tả tệp cơ bản sẽ được giữ mở khi đóng tệp. Nếu tên tệp được cung cấp closefd phải là
def any[iterable]: for element in iterable: if element: return True return False09 [mặc định];
Có thể sử dụng công cụ mở tùy chỉnh bằng cách chuyển một công cụ mở có thể gọi được. Bộ mô tả tệp cơ bản cho đối tượng tệp sau đó được lấy bằng cách gọi trình mở với [tệp, cờ]. công cụ mở phải trả về một bộ mô tả tệp đang mở [việc chuyển dưới dạng công cụ mở dẫn đến chức năng tương tự như chuyển
def any[iterable]: for element in iterable: if element: return True return False83]
Tệp mới được tạo là
Ví dụ sau sử dụng tham số của hàm để mở tệp liên quan đến thư mục đã cho
def any[iterable]: for element in iterable: if element: return True return False7
Loại trả về của hàm phụ thuộc vào chế độ. When được sử dụng để mở một tệp ở chế độ văn bản [_______33_______38,
class C: @classmethod def f[cls, arg1, arg2]: ...37,
>>> 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']09,
class C: @classmethod def f[cls, arg1, arg2]: ...50, v.v. ], nó trả về một lớp con của [cụ thể là ]. Khi được sử dụng để mở tệp ở chế độ nhị phân với bộ đệm, lớp được trả về là lớp con của. Lớp chính xác khác nhau. ở chế độ đọc nhị phân, nó trả về một ; . Khi bộ đệm bị tắt, luồng thô, một lớp con của , , được trả về
Xem thêm các mô-đun xử lý tệp, chẳng hạn như , [nơi được khai báo], , , và
Đưa ra một
>>> 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']26 với các đối số
>>> 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']27,
>>> 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']28,
>>> 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']29
Các đối số
>>> 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']28 và
>>> 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']29 có thể đã được sửa đổi hoặc suy ra từ cuộc gọi ban đầu
Thay đổi trong phiên bản 3. 3
Tham số mở đã được thêm vào
Chế độ
class C: @classmethod def f[cls, arg1, arg2]: ...
39 đã được thêm vàođã từng được nuôi dưỡng, bây giờ nó là bí danh của
hiện được nâng lên nếu tệp được mở ở chế độ tạo độc quyền [_______33_______39] đã tồn tại
Thay đổi trong phiên bản 3. 4
Tệp hiện không thể kế thừa
Thay đổi trong phiên bản 3. 5
Nếu cuộc gọi hệ thống bị gián đoạn và trình xử lý tín hiệu không đưa ra ngoại lệ, thì chức năng này sẽ thử lại cuộc gọi hệ thống thay vì đưa ra một ngoại lệ [xem PEP 475 để biết lý do]
Trình xử lý lỗi
class C: @classmethod def f[cls, arg1, arg2]: ...
81 đã được thêm vào
Thay đổi trong phiên bản 3. 6
Đã thêm hỗ trợ để chấp nhận các đối tượng triển khai
Trên Windows, việc mở bộ đệm bảng điều khiển có thể trả về một lớp con khác với
Đã thay đổi trong phiên bản 3. 11. Chế độ
>>> 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']42 đã bị xóa. ord[c]
Đưa ra một chuỗi đại diện cho một ký tự Unicode, trả về một số nguyên đại diện cho điểm mã Unicode của ký tự đó. Ví dụ:
>>> 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']43 trả về số nguyên
>>> 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']44 và
>>> 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']45 [ký hiệu Euro] trả về
>>> 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']46. Đây là nghịch đảo củapow[base , exp , mod=None]
Trả lại cơ sở cho điểm kinh nghiệm sức mạnh; . Dạng hai đối số
>>> 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']49 tương đương với việc sử dụng toán tử lũy thừa.
>>> 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']50
Các đối số phải có kiểu số. Với các loại toán hạng hỗn hợp, các quy tắc cưỡng chế cho các toán tử số học nhị phân được áp dụng. Đối với toán hạng, kết quả có cùng kiểu với toán hạng [sau khi ép buộc] trừ khi đối số thứ hai là âm; . Ví dụ:
>>> 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']52 trả về
>>> 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']53, nhưng
>>> 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']54 trả về
>>> 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']55. Đối với một cơ số âm của loại hoặc và một số mũ không tách rời, một kết quả phức tạp được đưa ra. Ví dụ,
>>> 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']58 trả về một giá trị gần với
>>> 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']59
Đối với toán hạng cơ sở và exp, nếu có mod, mod cũng phải là kiểu số nguyên và mod phải khác không. Nếu có mod và exp âm, cơ sở phải tương đối nguyên tố với mod. Trong trường hợp đó,
>>> 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']61 được trả về, trong đó inv_base là nghịch đảo của mod modulo cơ sở
Đây là một ví dụ về tính toán nghịch đảo cho
>>> 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']62 modulo
>>> 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']44
def any[iterable]: for element in iterable: if element: return True return False8
Đã thay đổi trong phiên bản 3. 8. Đối với toán hạng, dạng ba đối số của
>>> 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']65 hiện cho phép đối số thứ hai là số âm, cho phép tính toán các nghịch đảo mô-đun.
Đã thay đổi trong phiên bản 3. 8. Cho phép đối số từ khóa. Trước đây, chỉ các đối số vị trí được hỗ trợ.
in[*objects , sep=' ' , end='\n' , file=None , flush=False]In các đối tượng vào tệp luồng văn bản, được phân tách bằng sep và theo sau là end. sep, end, file và flush, nếu có, phải được cung cấp dưới dạng đối số từ khóa
Tất cả các đối số không phải từ khóa được chuyển đổi thành các chuỗi như hiện và được ghi vào luồng, được phân tách bằng sep và theo sau là kết thúc. Cả sep và end đều phải là chuỗi; . Nếu không có đối tượng nào được đưa ra, sẽ chỉ viết kết thúc
The file argument must be an object with a
>>> 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']69 method; if it is not present or
def any[iterable]: for element in iterable: if element: return True return False83, will be used. Vì các đối số được in được chuyển đổi thành chuỗi văn bản nên không thể sử dụng với các đối tượng tệp chế độ nhị phân. Đối với những thứ này, hãy sử dụng
>>> 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']73 thay thế
Việc đầu ra có được lưu vào bộ đệm hay không thường được xác định bởi tệp, nhưng nếu đối số từ khóa tuôn ra là đúng, thì luồng bị buộc phải xóa
Đã thay đổi trong phiên bản 3. 3. Đã thêm đối số từ khóa flush.
lớp property[fget=None , fset=None , fdel=None , doc=None]Trả về thuộc tính thuộc tính
fget là một chức năng để nhận một giá trị thuộc tính. fset là một chức năng để thiết lập một giá trị thuộc tính. fdel là một chức năng để xóa một giá trị thuộc tính. Và doc tạo một chuỗi tài liệu cho thuộc tính
Cách sử dụng điển hình là xác định thuộc tính được quản lý
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'15
def any[iterable]: for element in iterable: if element: return True return False9
Nếu c là một thể hiện của C, thì
>>> 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']75 sẽ gọi getter,
>>> 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']76 sẽ gọi setter và
>>> 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']77 deleter
Nếu được cung cấp, doc sẽ là chuỗi tài liệu của thuộc tính thuộc tính. Nếu không, thuộc tính sẽ sao chép chuỗi tài liệu của fget [nếu nó tồn tại]. Điều này cho phép dễ dàng tạo các thuộc tính chỉ đọc bằng cách sử dụng như một
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'0
Trình trang trí
>>> 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']79 biến phương thức
>>> 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']80 thành một "getter" cho thuộc tính chỉ đọc có cùng tên và nó đặt chuỗi tài liệu cho điện áp thành "Lấy điện áp hiện tại. ”
Một đối tượng thuộc tính có các phương thức
>>> 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']81,
>>> 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']82 và
>>> 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']83 có thể sử dụng làm trình trang trí để tạo một bản sao của thuộc tính với hàm truy cập tương ứng được đặt thành hàm được trang trí. Điều này được giải thích tốt nhất với một ví dụ
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'1
Mã này hoàn toàn tương đương với ví dụ đầu tiên. Đảm bảo cung cấp cho các chức năng bổ sung cùng tên với thuộc tính ban đầu [
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'15 trong trường hợp này. ]
Đối tượng thuộc tính được trả về cũng có các thuộc tính
>>> 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']85,
>>> 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']86 và
>>> 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']87 tương ứng với các đối số hàm tạo
Đã thay đổi trong phiên bản 3. 5. Các chuỗi tài liệu của các đối tượng thuộc tính hiện có thể ghi được.
lớp range[stop]class range[start , stop , step=1]Thay vì là một chức năng, thực sự là một loại trình tự bất biến, như được ghi lại trong và
repr[object]Trả về một chuỗi chứa một đại diện có thể in được của một đối tượng. Đối với nhiều loại, hàm này cố gắng trả về một chuỗi sẽ tạo ra một đối tượng có cùng giá trị khi được chuyển đến; . Một lớp có thể kiểm soát những gì hàm này trả về cho các phiên bản của nó bằng cách xác định phương thức
>>> 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']90. Nếu không truy cập được, chức năng này sẽ tăngđảo ngược[seq]
Trả lại một đảo ngược. seq phải là một đối tượng có phương thức
>>> 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']93 hoặc hỗ trợ giao thức trình tự [phương thức
>>> 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']94 và phương thức
class C: @classmethod def f[cls, arg1, arg2]: ...01 với các đối số nguyên bắt đầu từ
def any[iterable]: for element in iterable: if element: return True return False92]vòng[number , ndigits=None]
Trả về số được làm tròn chính xác đến n chữ số sau dấu thập phân. Nếu ndigits bị bỏ qua hoặc là
def any[iterable]: for element in iterable: if element: return True return False83, nó sẽ trả về số nguyên gần nhất với đầu vào của nó
Đối với các loại tích hợp hỗ trợ , các giá trị được làm tròn thành bội số gần nhất của 10 thành lũy thừa trừ n chữ số; . Mọi giá trị số nguyên đều hợp lệ cho n chữ số [dương, 0 hoặc âm]. Giá trị trả về là một số nguyên nếu ndigits bị bỏ qua hoặc
def any[iterable]: for element in iterable: if element: return True return False83. Mặt khác, giá trị trả về có cùng loại với số
Đối với một đối tượng Python chung
>>> 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']]05,
>>> 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']]06 ủy quyền cho
>>> 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']]07
Ghi chú
Hành vi của for float có thể gây ngạc nhiên. ví dụ:
>>> 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']]09 cho
>>> 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']]10 thay vì dự kiến là
>>> 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']]11. Đây không phải là một lỗi. đó là kết quả của thực tế là hầu hết các phân số thập phân không thể được biểu diễn chính xác dưới dạng số float. Xem để biết thêm thông tinlớp setclass set[iterable]
Trả về một đối tượng mới, tùy chọn với các phần tử được lấy từ iterable.
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'37 là một lớp tích hợp. Xem và để biết tài liệu về lớp học này
For other containers see the built-in , , , and classes, as well as the module
setattr[object , name , value]Đây là bản sao của. Các đối số là một đối tượng, một chuỗi và một giá trị tùy ý. Chuỗi có thể đặt tên cho một thuộc tính hiện có hoặc một thuộc tính mới. Hàm gán giá trị cho thuộc tính, miễn là đối tượng cho phép. Ví dụ,
>>> 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']]21 tương đương với
>>> 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']]22
tên không cần phải là mã định danh Python như được định nghĩa trong trừ khi đối tượng chọn thực thi điều đó, ví dụ như trong tùy chỉnh hoặc thông qua. Một thuộc tính có tên không phải là mã định danh sẽ không thể truy cập được bằng cách sử dụng ký hiệu dấu chấm, nhưng có thể truy cập được thông qua v.v.
Ghi chú
Vì xảy ra vào thời điểm biên dịch, người ta phải xáo trộn tên của một thuộc tính riêng [các thuộc tính có hai dấu gạch dưới ở đầu] theo cách thủ công để đặt tên đó với
lớp slice[stop]class slice[start , stop , step=1]Trả về một đối tượng đại diện cho tập hợp các chỉ số được chỉ định bởi
>>> 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']]27. Đối số bắt đầu và bước mặc định là
def any[iterable]: for element in iterable: if element: return True return False83. Các đối tượng lát cắt có các thuộc tính dữ liệu chỉ đọc
>>> 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']]29,
>>> 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']]30 và
>>> 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']]31 chỉ trả về các giá trị đối số [hoặc giá trị mặc định của chúng]. They have no other explicit functionality; however, they are used by NumPy and other third-party packages. Các đối tượng lát cũng được tạo khi sử dụng cú pháp lập chỉ mục mở rộng. Ví dụ.
>>> 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']]32 hoặc
>>> 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']]33. Xem phiên bản thay thế trả về một trình vòng lặpđã sắp xếp[iterable , / , * , key=None , reverse=False]
Trả về một danh sách được sắp xếp mới từ các mục trong iterable
Có hai đối số tùy chọn phải được chỉ định làm đối số từ khóa
key chỉ định chức năng của một đối số được sử dụng để trích xuất khóa so sánh từ mỗi phần tử trong iterable [ví dụ:
>>> 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']]35]. Giá trị mặc định là
def any[iterable]: for element in iterable: if element: return True return False83 [so sánh trực tiếp các phần tử]
đảo ngược là một giá trị boolean. Nếu được đặt thành
def any[iterable]: for element in iterable: if element: return True return False09, thì các thành phần danh sách được sắp xếp như thể mỗi so sánh được đảo ngược
Sử dụng để chuyển đổi chức năng cmp kiểu cũ thành chức năng chính
Chức năng tích hợp được đảm bảo ổn định. Một sắp xếp ổn định nếu nó đảm bảo không thay đổi thứ tự tương đối của các phần tử được so sánh bằng nhau — điều này hữu ích cho việc sắp xếp theo nhiều lần [ví dụ: sắp xếp theo bộ phận, sau đó theo bậc lương]
Thuật toán sắp xếp chỉ sử dụng _______96_______40 phép so sánh giữa các mục. Mặc dù xác định một phương thức sẽ đủ để sắp xếp, PEP 8 khuyến nghị rằng cả sáu phương thức đều được triển khai. Điều này sẽ giúp tránh lỗi khi sử dụng cùng một dữ liệu với các công cụ đặt hàng khác, chẳng hạn như dựa trên một phương pháp cơ bản khác. Việc triển khai tất cả sáu phép so sánh cũng giúp tránh nhầm lẫn đối với các phép so sánh hỗn hợp có thể gọi phản ánh phương thức
Để biết các ví dụ sắp xếp và hướng dẫn sắp xếp ngắn gọn, hãy xem
@staticmethodChuyển đổi một phương thức thành một phương thức tĩnh
Một phương thức tĩnh không nhận được đối số đầu tiên ngầm định. Để khai báo một phương thức tĩnh, hãy sử dụng thành ngữ này
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'2
Biểu mẫu
>>> 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']]44 là một hàm – xem để biết chi tiết
Một phương thức tĩnh có thể được gọi trên lớp [chẳng hạn như
def any[iterable]: for element in iterable: if element: return True return False65] hoặc trên một thể hiện [chẳng hạn như
def any[iterable]: for element in iterable: if element: return True return False66]. Hơn nữa, chúng có thể được gọi là các hàm thông thường [chẳng hạn như
>>> 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']]47]
Các phương thức tĩnh trong Python tương tự như các phương thức được tìm thấy trong Java hoặc C++. Ngoài ra, hãy xem một biến thể hữu ích để tạo các hàm tạo lớp thay thế
Giống như tất cả các bộ trang trí, cũng có thể gọi
>>> 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']]49 như một hàm thông thường và làm điều gì đó với kết quả của nó. Điều này là cần thiết trong một số trường hợp khi bạn cần tham chiếu đến một hàm từ phần thân của lớp và bạn muốn tránh việc tự động chuyển đổi thành phương thức thể hiện. Đối với những trường hợp này, hãy sử dụng thành ngữ này
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'3
Để biết thêm thông tin về các phương pháp tĩnh, xem
Đã thay đổi trong phiên bản 3. 10. Các phương thức tĩnh hiện kế thừa các thuộc tính của phương thức [
def any[iterable]: for element in iterable: if element: return True return False69,
def any[iterable]: for element in iterable: if element: return True return False70,
def any[iterable]: for element in iterable: if element: return True return False71,
def any[iterable]: for element in iterable: if element: return True return False72 và
def any[iterable]: for element in iterable: if element: return True return False73], có thuộc tính mới
def any[iterable]: for element in iterable: if element: return True return False74 và hiện có thể gọi được như các hàm thông thường. lớp str[object='']class str[object=b'' , encoding='utf-8' , errors='strict']
Trả về một phiên bản của đối tượng. Xem để biết chi tiết
class C: @classmethod def f[cls, arg1, arg2]: ...58 là chuỗi tích hợp. Để biết thông tin chung về chuỗi, xemsum[iterable , / , start=0]
Tính tổng bắt đầu và các mục của một lần lặp từ trái sang phải và trả về tổng. Các mục của iterable thường là các số và giá trị bắt đầu không được phép là một chuỗi
Đối với một số trường hợp sử dụng, có những lựa chọn thay thế tốt cho. Cách ưa thích, nhanh chóng để nối một chuỗi các chuỗi là bằng cách gọi
>>> 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']]60. Để thêm các giá trị dấu phẩy động với độ chính xác mở rộng, hãy xem. Để nối một loạt các lần lặp, hãy cân nhắc sử dụng
Đã thay đổi trong phiên bản 3. 8. Tham số bắt đầu có thể được chỉ định làm đối số từ khóa.
hạng superclass super[type , object_or_type=None]Trả về một đối tượng proxy ủy thác các cuộc gọi phương thức cho một loại cha hoặc anh chị em. Điều này rất hữu ích để truy cập các phương thức kế thừa đã bị ghi đè trong một lớp
object_or_type xác định đối tượng được tìm kiếm. Việc tìm kiếm bắt đầu từ lớp ngay sau loại
Ví dụ: nếu object_or_type là
>>> 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']]64 và giá trị của loại là
>>> 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']]65, thì hãy tìm kiếm
>>> 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']]67
The attribute of the object_or_type lists the method resolution search order used by both and . Thuộc tính động và có thể thay đổi bất cứ khi nào hệ thống phân cấp thừa kế được cập nhật
Nếu đối số thứ hai bị bỏ qua, siêu đối tượng được trả về không bị ràng buộc. If the second argument is an object,
>>> 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']]71 must be true. If the second argument is a type,
>>> 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']]72 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
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'4
In addition to method lookups, also works for attribute lookups. One possible use case for this is calling in a parent or sibling class
Note that is implemented as part of the binding process for explicit dotted attribute lookups such as
>>> 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']]75. It does so by implementing its own
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'42 method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, is undefined for implicit lookups using statements or operators such as
>>> 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']]78
Also note that, aside from the zero argument form, 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 , see guide to using super[]
class tupleclass tuple[iterable]Thay vì là một chức năng, thực sự là một loại trình tự bất biến, như được ghi lại trong và
class type[object]class type[name , cơ sở , 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
The 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 statement. The name string is the class name and becomes the attribute. The bases tuple contains the base classes and becomes the attribute; if empty, , 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 attribute. The following two statements create identical objects
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'5
Xem thêm
Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery [usually ] in the same way that keywords in a class definition [besides metaclass] would
Xem thêm
Changed in version 3. 6. Subclasses of which don’t override
>>> 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']]92 may no longer use the one-argument form to get the type of an object. vars[]vars[object]
Return the attribute for a module, class, instance, or any other object with a attribute
Objects such as modules and instances have an updateable attribute; however, other objects may have write restrictions on their attributes [for example, classes use a to prevent direct dictionary updates]
Without an argument, acts like . Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored
A exception is raised if an object is specified but it doesn’t have a attribute [for example, if its class defines the attribute]
zip[*iterables , strict=False]Iterate over several iterables in parallel, producing tuples with an item from each one
Example
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'6
More formally. 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 is that it turns rows into columns, and columns into rows. This is similar to transposing a matrix
is lazy. The elements won’t be processed until the iterable is iterated on, e. g. by a
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 106 loop or by wrapping in a
One thing to consider is that the iterables passed to 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, 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
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'
7is often used in cases where the iterables are assumed to be of equal length. In such cases, it’s recommended to use the
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 1
11 option. Its output is the same as regular>>> bin[3] '0b11' >>> bin[-10] '-0b1010'
8Unlike the default behavior, it raises a if one iterable is exhausted before the others
>>> bin[3] '0b11' >>> bin[-10] '-0b1010'
9Without the
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 1
11 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 programShorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by
Edge cases. With a single iterable argument, 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
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 1
17. This repeats the same iteratordef enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 1
18 times so that each output tuple has the result ofdef enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 1
18 calls to the iterator. This has the effect of dividing the input into n-length chunksin conjunction with the
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 1
21 operator can be used to unzip a list>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']
0
Changed in version 3. 10. Added the
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 122 argument. __import__[name , globals=None , locals=None , fromlist=[] , level=0]
Ghi chú
This is an advanced function that is not needed in everyday Python programming, unlike
This function is invoked by the statement. It can be replaced [by importing the module and assigning to
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 126] in order to change semantics of the
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 124 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 is also discouraged in favor of
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 statement
level specifies whether to use absolute or relative imports.
def any[iterable]: for element in iterable: if element: return True return False92 [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 [see PEP 328 for the details]
When the name variable is of the form
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 133, 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
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 134 results in bytecode resembling the following code
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']1
The statement
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 135 results in this call
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']2
Note how returns the toplevel module here because this is the object that is bound to a name by the statement
On the other hand, the statement
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 138 results in
>>> format[14, '#b'], format[14, 'b'] ['0b1110', '1110'] >>> f'{14:#b}', f'{14:b}' ['0b1110', '1110']3
Here, the
def enumerate[iterable, start=0]: n = start for elem in iterable: yield n, elem n += 139 module is returned from . 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
Changed in version 3. 3. Negative values for level are no longer supported [which also changes the default value to 0].
Changed in version 3. 9. When the command line options or are being used, the environment variable is now ignored.
Footnotes
Note that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines