Teks sumber — English
Terjemahan — Bahasa Indonesia
Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the :func:`repr` function or the slightly different :func:`str` function). The latter function is implicitly used when an object is written by the :func:`print` function.
Beberapa operasi didukung oleh beberapa jenis objek; khususnya, secara praktis semua objek dapat dibandingkan untuk kesetaraan, diuji untuk nilai kebenaran, dan dikonversi ke string (dengan fungsi :func:`repr` atau yang sedikit berbeda fungsi :func:`str`). Fungsi terakhir secara implisit digunakan ketika suatu objek ditulis oleh fungsi :func:`print`.
By default, an object is considered true unless its class defines either a :meth:`~object.__bool__` method that returns ``False`` or a :meth:`~object.__len__` method that returns zero, when called with the object. [1]_ If one of the methods raises an exception when called, the exception is propagated and the object does not have a truth value (for example, :data:`NotImplemented`). Here are most of the built-in objects considered false:
Unless stated otherwise, objects of different types never compare equal. The ``==`` operator is always defined but for some object types (for example, class objects) is equivalent to :keyword:`is`. The ``<``, ``<=``, ``>`` and ``>=`` operators are only defined where they make sense; for example, they raise a :exc:`TypeError` exception when one of the arguments is a complex number.
The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be customized; also they can be applied to any two objects and never raise an exception.
One method needs to be defined for container objects to provide :term:`iterable` support:
Return an :term:`iterator` object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C API.
The iterator objects themselves are required to support the following two methods, which together form the :dfn:`iterator protocol`:
Return the :term:`iterator` object itself. This is required to allow both containers and iterators to be used with the :keyword:`for` and :keyword:`in` statements. This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C API.
Return the next item from the :term:`iterator`. If there are no further items, raise the :exc:`StopIteration` exception. This method corresponds to the :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for Python objects in the Python/C API.
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.
One common use for generator functions is implementing the :meth:`~object.__iter__` method of custom iterable objects. For example::
There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of :ref:`binary data <binaryseq>` and :ref:`text strings <textseq>` are described in dedicated sections.
if concatenating :class:`str` objects, you can build a list and use :meth:`str.join` at the end or else write to an :class:`io.StringIO` instance and retrieve its value when complete
if concatenating :class:`bytes` objects, you can similarly use :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place concatenation with a :class:`bytearray` object. :class:`bytearray` objects are mutable and have an efficient overallocation mechanism
if concatenating :class:`tuple` objects, extend a :class:`list` instead
For detailed information on thread-safety guarantees for :class:`list` objects, see :ref:`thread-safety-list`.
Ranges implement all of the :ref:`common <typesseq-common>` sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).
Range objects implement the :class:`collections.abc.Sequence` ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see :ref:`typesseq`):
Testing range objects for equality with ``==`` and ``!=`` compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step` attributes, for example ``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.)
Implement the Sequence ABC. Support slicing and negative indices. Test :class:`int` objects for membership in constant time instead of iterating through all items.
Define '==' and '!=' to compare range objects based on the sequence of values they define (instead of comparing based on object identity).
Textual data in Python is handled with :class:`str` objects, or :dfn:`strings`. Strings are immutable :ref:`sequences <typesseq>` of Unicode code points. String literals are written in a variety of ways:
Strings may also be created from other objects using the :class:`str` constructor.
If neither *encoding* nor *errors* is given, ``str(object)`` returns :meth:`type(object).__str__(object) <object.__str__>`, which is the "informal" or nicely printable string representation of *object*. For string objects, this is the string itself. If *object* does not have a :meth:`~object.__str__` method, then :func:`str` falls back to returning :func:`repr(object) <repr>`.
If at least one of *encoding* or *errors* is given, *object* should be a :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object, then ``str(bytes, encoding, errors)`` is equivalent to :meth:`bytes.decode(encoding, errors) <bytes.decode>`. Otherwise, the bytes object underlying the buffer object is obtained before calling :meth:`bytes.decode`. See :ref:`binaryseq` and :ref:`bufferobjects` for information on buffer objects.
Return a string which is the concatenation of the strings in *iterable*. A :exc:`TypeError` will be raised if there are any non-string values in *iterable*, including :class:`bytes` objects. The separator between elements is the string providing this method. For example:
String objects have one unique built-in operation: the ``%`` operator (modulo). This is also known as the string *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a string), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language. For example:
The core built-in types for manipulating binary data are :class:`bytes` and :class:`bytearray`. They are supported by :class:`memoryview` which uses the :ref:`buffer protocol <bufferobjects>` to access the memory of other binary objects without needing to make a copy.
Bytes Objects
Bayt Nesneleri
Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.
While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that ``0 <= x < 256`` (attempts to violate this restriction will trigger :exc:`ValueError`). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).
In addition to the literal forms, bytes objects can be created in a number of other ways:
:meth:`bytes.fromhex` now accepts ASCII :class:`bytes` and :term:`bytes-like objects <bytes-like object>` as input.
Since bytes objects are sequences of integers (akin to a tuple), for a bytes object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
The representation of bytes objects uses the literal format (``b'...'``) since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can always convert a bytes object into a list of integers using ``list(b)``.
Bytearray Objects
:class:`bytearray` objects are a mutable counterpart to :class:`bytes` objects.
There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:
As bytearray objects are mutable, they support the :ref:`mutable <typesseq-mutable>` sequence operations in addition to the common bytes and bytearray operations described in :ref:`bytes-methods`.
:meth:`bytearray.fromhex` now accepts ASCII :class:`bytes` and :term:`bytes-like objects <bytes-like object>` as input.
Since bytearray objects are sequences of integers (akin to a list), for a bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
The representation of bytearray objects uses the bytes literal format (``bytearray(b'...')``) since it is often more useful than e.g. ``bytearray([46, 46, 46])``. You can always convert a bytearray object into a list of integers using ``list(b)``.
For detailed information on thread-safety guarantees for :class:`bytearray` objects, see :ref:`thread-safety-bytearray`.
Both bytes and bytearray objects support the :ref:`common <typesseq-common>` sequence operations. They interoperate not just with operands of the same type, but with any :term:`bytes-like object`. Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands.
The methods on bytes and bytearray objects don't accept strings as their arguments, just as the methods on strings don't accept bytes as their arguments. For example, you have to write::
The following methods on bytes and bytearray objects can be used with arbitrary binary data.
Return a bytes or bytearray object which is the concatenation of the binary data sequences in *iterable*. A :exc:`TypeError` will be raised if there are any values in *iterable* that are not :term:`bytes-like objects <bytes-like object>`, including :class:`str` objects. The separator between elements is the contents of the bytes or bytearray object providing this method.
This static method returns a translation table usable for :meth:`bytes.translate` that will map each character in *from* into the character at the same position in *to*; *from* and *to* must both be :term:`bytes-like objects <bytes-like object>` and have the same length.
Split the sequence at the first occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects.
Split the sequence at the last occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence.
The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do *not* operate in place, and instead produce new objects.
Return a copy of the object centered in a sequence of length *width*. Padding is done using the specified *fillbyte* (default is an ASCII space). For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(s)``.
Return a copy of the object left justified in a sequence of length *width*. Padding is done using the specified *fillbyte* (default is an ASCII space). For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(s)``.
Return a copy of the object right justified in a sequence of length *width*. Padding is done using the specified *fillbyte* (default is an ASCII space). For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(s)``.
The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do *not* operate in place, and instead produce new objects.
Return a copy of the sequence left filled with ASCII ``b'0'`` digits to make a sequence of length *width*. A leading sign prefix (``b'+'``/ ``b'-'``) is handled by inserting the padding *after* the sign character rather than before. For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(seq)``.
Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: the ``%`` operator (modulo). This is also known as the bytes *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a bytes object), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language.
Single byte (accepts integer or single byte objects).
Bytes (any object that follows the :ref:`buffer protocol <bufferobjects>` or has :meth:`~object.__bytes__`).
:class:`memoryview` objects allow Python code to access the internal data of an object that supports the :ref:`buffer protocol <bufferobjects>` without copying.
Create a :class:`memoryview` that references *object*. *object* must support the buffer protocol. Built-in objects that support the buffer protocol include :class:`bytes` and :class:`bytearray`.
If either format string is not supported by the :mod:`struct` module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical)::
Note that, as with floating-point numbers, ``v is w`` does *not* imply ``v == w`` for memoryview objects.
Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, a :class:`bytearray` would temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible.
For information on the thread safety of :class:`memoryview` objects in the :term:`free-threaded build`, see :ref:`thread-safety-memoryview`.
A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in :class:`dict`, :class:`list`, and :class:`tuple` classes, and the :mod:`collections` module.) See :ref:`time-complexity` for the costs of the various set operations.
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be :term:`hashable`. To represent sets of sets, the inner sets must be :class:`frozenset` objects. If *iterable* is not specified, a new empty set is returned.
For detailed information on thread-safety guarantees for :class:`set` objects, see :ref:`thread-safety-set`.
A :term:`mapping` object maps :term:`hashable` values to arbitrary objects. There are currently two standard mapping types, the :dfn:`dictionary` and :class:`frozendict`. (For other containers see the built-in :class:`list`, :class:`set`, and :class:`tuple` classes, and the :mod:`collections` module.) See :ref:`time-complexity` for the costs of the various dictionary operations.
Return a new view of the dictionary's items (``(key, value)`` pairs). See the :ref:`documentation of view objects <dict-views>`.
Return a new view of the dictionary's keys. See the :ref:`documentation of view objects <dict-views>`.
Return a new view of the dictionary's values. See the :ref:`documentation of view objects <dict-views>`.
For detailed information on thread-safety guarantees for :class:`dict` objects, see :ref:`thread-safety-dict`.
Dictionary view objects
The objects returned by :meth:`dict.keys`, :meth:`dict.values` and :meth:`dict.items` are *view objects*. They provide a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes.
>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()
>>> # iteration
>>> n = 0
>>> for val in values:
... n += val
...
>>> print(n)
504
>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']
>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
True
>>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
True
>>> # get back a read-only proxy for the original dictionary
>>> values.mapping
mappingproxy({'bacon': 1, 'spam': 500})
>>> values.mapping['spam']
500
An example of a context manager that returns itself is a :term:`file object`. File objects return themselves from __enter__() to allow :func:`open` to be used as the context expression in a :keyword:`with` statement.
Python defines several context managers to support easy thread synchronisation, prompt closure of files or other objects, and simpler manipulation of the active decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the :mod:`contextlib` module for some examples.
Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible.
``GenericAlias`` objects are generally created by :ref:`subscripting <subscriptions>` a class. They are most often used with :ref:`container classes <sequence-types>`, such as :class:`list` or :class:`dict`. For example, ``list[int]`` is a ``GenericAlias`` object created by subscripting the ``list`` class with the argument :class:`int`. ``GenericAlias`` objects are intended primarily for use with :term:`type annotations <annotation>`.
If ``x = re.search('foo', 'foo')``, ``x`` will be a :ref:`re.Match <match-objects>` object where the return values of ``x.group(0)`` and ``x[0]`` will both be of type :class:`str`. We can represent this kind of object in type annotations with the ``GenericAlias`` ``re.Match[str]``.
If ``y = re.search(b'bar', b'bar')``, (note the ``b`` for :class:`bytes`), ``y`` will also be an instance of ``re.Match``, but the return values of ``y.group(0)`` and ``y[0]`` will both be of type :class:`bytes`. In type annotations, we would represent this variety of :ref:`re.Match <match-objects>` objects with ``re.Match[bytes]``.
``GenericAlias`` objects are instances of the class :class:`types.GenericAlias`, which can also be used to create ``GenericAlias`` objects directly. Specializations of user-defined :ref:`generic classes <generic-classes>` may not be instances of :class:`types.GenericAlias`, but they provide similar functionality.
Another example for :term:`mapping` objects, using a :class:`dict`, which is a generic type expecting two type parameters representing the key type and the value type. In this example, the function expects a ``dict`` with keys of type :class:`str` and values of type :class:`int`::
:ref:`re.Pattern <re-objects>`
:ref:`re.Match <match-objects>`
Special Attributes of ``GenericAlias`` objects
A union object holds the value of the ``|`` (bitwise or) operation on multiple :ref:`type objects <bltin-type-objects>`. These types are intended primarily for :term:`type annotations <annotation>`. The union type expression enables cleaner type hinting syntax compared to subscripting :class:`typing.Union`.
Union objects can be tested for equality with other union objects. Details:
However, :ref:`parameterized generics <types-genericalias>` in union objects cannot be checked::
The :meth:`!__or__` method for type objects was added to support the syntax ``X | Y``. If a metaclass implements :meth:`!__or__`, it may override the default behavior of creating a union:
Union objects are now instances of :class:`typing.Union`. Previously, they were instances of :class:`types.UnionType`, which remains an alias for :class:`typing.Union`.
The interpreter supports several other kinds of objects. Most of these support only one or two operations.
See :ref:`objects` and :ref:`class` for these.
Function objects are created by function definitions. The only operation on a function object is to call it: ``func(argument-list)``.
There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.
Like :ref:`function objects <user-defined-funcs>`, bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (:attr:`method.__func__`), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an :exc:`AttributeError` being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:
Code Objects
Objek Kode
Code objects are used by the implementation to represent "pseudo-compiled" executable Python code such as a function body. They differ from function objects because they don't contain a reference to their global execution environment. Code objects are returned by the built-in :func:`compile` function and can be extracted from function objects through their :attr:`~function.__code__` attribute. See also the :mod:`code` module.
Type Objects
Objek Tipe
Type objects represent the various object types. An object's type is accessed by the built-in function :func:`type`. There are no special operations on types. The standard module :mod:`types` defines names for all standard built-in types.
Python also uses three dots in ways that are not ``Ellipsis`` objects, for instance:
Internal Objects
See :ref:`types` for this information. It describes :ref:`stack frame objects <frame-objects>`, :ref:`traceback objects <traceback-objects>`, and slice objects.
objects