Teks sumber — English
Terjemahan — Bahasa Indonesia
The *value* of some objects can change. Objects whose value can change are said to be *mutable*; objects whose value is unchangeable once they are created are called *immutable*. (The value of an immutable container object that contains a reference to a mutable object can change when the latter's value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object's mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.
Some objects contain references to other objects; these are called *containers*. Examples of containers are tuples, lists and dictionaries. The references are part of a container's value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.
Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. For example, after ``a = 1; b = 1``, *a* and *b* may or may not refer to the same object with the value one, depending on the implementation. This is because :class:`int` is an immutable type, so the reference to ``1`` can be reused. This behaviour depends on the implementation used, so should not be relied upon, but is something to be aware of when making use of object identity tests. However, after ``c = []; d = []``, *c* and *d* are guaranteed to refer to two different, unique, newly created empty lists. (Note that ``e = f = []`` assigns the *same* object to both *e* and *f*.)
Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), although such additions will often be provided via the standard library instead.
Some of the type descriptions below contain a paragraph listing 'special attributes.' These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future.
The items of a :class:`tuple` are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a 'singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.
Lists
List
The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.)
These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key's hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index the same dictionary entry.
A user-defined function object is created by a function definition (see section :ref:`function`). It should be called with an argument list containing the same number of items as the function's formal parameter list.
When an instance method object is called, the underlying function (:attr:`~method.__func__`) is called, inserting the class instance (:attr:`~method.__self__`) in front of the argument list. For instance, when :class:`!C` is a class which contains a definition for a function :meth:`!f`, and ``x`` is an instance of :class:`!C`, calling ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``.
This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is ``alist.append()``, assuming *alist* is a list object. In this case, the special read-only attribute :attr:`!__self__` is set to the object denoted by *alist*. (The attribute has the same semantics as it does with :attr:`other instance methods <method.__self__>`.)
With the exception of :attr:`~module.__name__`, it is **strongly** recommended that you rely on :attr:`~module.__spec__` and its attributes instead of any of the other individual attributes listed in this subsection. Note that updating an attribute on :attr:`!__spec__` will not update the corresponding attribute on the module itself:
As well as the import-related attributes listed above, module objects also have the following writable attributes:
The module's namespace as a dictionary object. Uniquely among the attributes listed here, :attr:`!__dict__` cannot be accessed as a global variable from within a module; it can only be accessed as an attribute on module objects.
Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. The list is in definition order. Example:
File objects implement common methods, listed below, to simplify usage in generic code. They are expected to be :ref:`context-managers`.
This positional information can be missing. A non-exhaustive lists of cases where this may happen:
When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. (One example of this is the :ref:`NodeList <dom-nodelist-objects>` interface in the W3C's Document Object Model.)
Called when :func:`dir` is called on the object. An iterable must be returned. :func:`dir` converts the returned iterable to a list and sorts it.
Without a :attr:`~object.__dict__` variable, instances cannot be assigned new variables not listed in the *__slots__* definition. Attempts to assign to an unlisted variable name raises :exc:`AttributeError`. If dynamic assignment of new variables is desired, then add ``'__dict__'`` to the sequence of strings in the *__slots__* declaration.
When using :term:`type annotations<annotation>`, it is often useful to *parameterize* a :term:`generic type` using Python's square-brackets notation. For example, the annotation ``list[int]`` might be used to signify a :class:`list` in which all the elements are of type :class:`int`.
In Python, all classes are themselves instances of other classes. The class of a class is known as that class's :term:`metaclass`, and most classes have the :class:`type` class as their metaclass. :class:`type` does not define :meth:`~object.__getitem__`, meaning that expressions such as ``list[int]``, ``dict[str, float]`` and ``tuple[str, bytes]`` all result in :meth:`~object.__class_getitem__` being called::
>>> # list has class "type" as its metaclass, like most classes:
>>> type(list)
<class 'type'>
>>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
True
>>> # "list[int]" calls "list.__class_getitem__(int)"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type(list[int])
<class 'types.GenericAlias'>
The following methods can be defined to implement container objects. None of them are provided by the :class:`object` class itself. Containers usually are :term:`sequences <sequence>` (such as :class:`lists <list>` or :class:`tuples <tuple>`) or :term:`mappings <mapping>` (like :term:`dictionaries <dictionary>`), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers *k* for which ``0 <= k < N`` where *N* is the length of the sequence, or :class:`slice` objects, which define a range of items. It is also recommended that mappings provide the methods :meth:`!keys`, :meth:`!values`, :meth:`!items`, :meth:`!get`, :meth:`!clear`, :meth:`!setdefault`, :meth:`!pop`, :meth:`!popitem`, :meth:`!copy`, and :meth:`!update` behaving similar to those for Python's standard :class:`dictionary <dict>` objects. The :mod:`collections.abc` module provides a :class:`~collections.abc.MutableMapping` :term:`abstract base class` to help create those methods from a base set of :meth:`~object.__getitem__`, :meth:`~object.__setitem__`, :meth:`~object.__delitem__`, and :meth:`!keys`.
Mutable sequences should provide methods :meth:`~sequence.append`, :meth:`~sequence.clear`, :meth:`~sequence.count`, :meth:`~sequence.extend`, :meth:`~sequence.index`, :meth:`~sequence.insert`, :meth:`~sequence.pop`, :meth:`~sequence.remove`, and :meth:`~sequence.reverse`, like Python standard :class:`list` objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods :meth:`~object.__add__`, :meth:`~object.__radd__`, :meth:`~object.__iadd__`, :meth:`~object.__mul__`, :meth:`~object.__rmul__` and :meth:`~object.__imul__` described below; they should not define other numerical operators.
Coroutines also have the methods listed below, which are analogous to those of generators (see :ref:`generator-methods`). However, unlike generators, coroutines do not directly support iteration.
list
list