Pelokalan
Python ID
id en
Masuk
Proyek
reference__datamodel.po Berkas proyek · python-docs-id-3.14 · Bahasa Indonesia
Modul PO Hanya lihat
Teks sumber — English
Terjemahan — Bahasa Indonesia
These represent elements from the mathematical set of integers (positive and negative).
These represent finite ordered sets indexed by non-negative numbers. The built-in function :func:`len` returns the number of items of a sequence. When the length of a sequence is *n*, the index set contains the numbers 0, 1, ..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``. Some sequences, including built-in sequences, interpret negative subscripts by adding the sequence length. For example, ``a[-2]`` equals ``a[n-2]``, the second to last item of sequence a with length ``n``.
Set types
These represent unordered, finite sets of unique, immutable objects. As such, they cannot be indexed by any subscript. However, they can be iterated over, and the built-in function :func:`len` returns the number of items in a set. Common uses for sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
For set elements, the same immutability rules apply as for dictionary keys. Note that numeric types obey the normal rules for numeric comparison: if two numbers compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a set.
There are currently two intrinsic set types:
Sets
Himpunan *Set*
These represent a mutable set. They are created by the built-in :func:`set` constructor and can be modified afterwards by several methods, such as :meth:`~set.add`.
Frozen sets
These represent an immutable set. They are created by the built-in :func:`frozenset` constructor. As a frozenset is immutable and :term:`hashable`, it can be used again as an element of another set, or as a dictionary key.
These represent finite sets of objects indexed by arbitrary index sets. The subscript notation ``a[k]`` selects the item indexed by ``k`` from the mapping ``a``; this can be used in expressions and as the target of assignments or :keyword:`del` statements. The built-in function :func:`len` returns the number of items in a mapping.
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.
These represent an immutable dictionary. They are created by the built-in :func:`frozendict` constructor. A frozendict is :term:`hashable` if all of its keys and values are hashable, in which case it can be used as an element of a set, or as a key in another mapping. :class:`!frozendict` is not a subclass of :class:`dict`; it inherits directly from :class:`object`.
A cell object has the attribute ``cell_contents``. This can be used to get the value of the cell, as well as set the value.
Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes.
Methods also support accessing (but not setting) the arbitrary function attributes on the underlying :ref:`function object <user-defined-funcs>`.
A function or method which contains a :keyword:`yield` expression (see section :ref:`yieldexpr`) is called a :dfn:`generator function`. Such a function, when called, always returns an :term:`iterator` object which can be used to execute the body of the function: calling the iterator's :meth:`iterator.__next__` method will cause the function to execute until it provides a value using the :keyword:`!yield` expression. When the function executes a :keyword:`return` statement or falls off the end, a :exc:`StopIteration` exception is raised and the iterator will have reached the end of the set of values to be returned.
Calling the asynchronous iterator's :meth:`aiterator.__anext__ <object.__anext__>` method will return an :term:`awaitable` which when awaited will execute until it provides a value using the :keyword:`yield` expression. When the function executes an empty :keyword:`return` statement or falls off the end, a :exc:`StopAsyncIteration` exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded.
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__>`.)
To create a module dynamically rather than using the import system, it's recommended to use :func:`importlib.util.module_from_spec`, which will set the various import-controlled attributes to appropriate values. It's also possible to use the :class:`types.ModuleType` constructor to create modules directly, but this technique is more error-prone, as most attributes must be manually set on the module object after it has been created when using this approach.
The name used to uniquely identify the module in the import system. For a directly executed module, this will be set to ``"__main__"``.
This attribute must be set to the fully qualified name of the module. It is expected to match the value of :attr:`module.__spec__.name <importlib.machinery.ModuleSpec.name>`.
Set to the :class:`module spec <importlib.machinery.ModuleSpec>` that was used when importing the module. See :ref:`module-specs` for more details.
If the module is top-level (that is, not a part of any specific package) then the attribute should be set to ``''`` (the empty string). Otherwise, it should be set to the name of the module's package (which can be equal to :attr:`module.__name__` if the module itself is a package). See :pep:`366` for further details.
This attribute is used instead of :attr:`~module.__name__` to calculate explicit relative imports for main modules. It defaults to ``None`` for modules created dynamically using the :class:`types.ModuleType` constructor; use :func:`importlib.util.module_from_spec` instead to ensure the attribute is set to a :class:`str`.
It is **strongly** recommended that you use :attr:`module.__spec__.parent <importlib.machinery.ModuleSpec.parent>` instead of :attr:`!module.__package__`. :attr:`__package__` is now only used as a fallback if :attr:`!__spec__.parent` is not set, and this fallback path is deprecated.
:attr:`!__package__` will cease to be set or taken into consideration by the import system or standard library.
:attr:`!__loader__` defaults to ``None`` for modules created dynamically using the :class:`types.ModuleType` constructor; use :func:`importlib.util.module_from_spec` instead to ensure the attribute is set to a :term:`loader` object.
Setting :attr:`!__loader__` on a module while failing to set :attr:`!__spec__.loader` is deprecated. In Python 3.16, :attr:`!__loader__` will cease to be set or taken into consideration by the import system or the standard library.
:attr:`!__file__` is an optional attribute that may or may not be set. Both attributes should be a :class:`str` when they are available.
An optional attribute, :attr:`!__file__` indicates the pathname of the file from which the module was loaded (if loaded from a file), or the pathname of the shared library file for extension modules loaded dynamically from a shared library. It might be missing for certain types of modules, such as C modules that are statically linked into the interpreter, and the :ref:`import system <importsystem>` may opt to leave it unset if it has no semantic meaning (for example, a module loaded from a database).
The ``__cached__`` attribute is no longer set on modules or taken into consideration by the import system or standard library.
The line number of the first line of the class definition, including decorators. Setting the :attr:`~type.__module__` attribute removes the :attr:`!__firstlineno__` item from the type's dictionary.
Attribute assignments and deletions update the instance's dictionary, never a class's dictionary. If the class has a :meth:`~object.__setattr__` or :meth:`~object.__delattr__` method, this is called instead of updating the instance dictionary directly.
The following flag bits are defined for :attr:`~codeobject.co_flags`: bit ``0x04`` is set if the function uses the ``*arguments`` syntax to accept an arbitrary number of positional arguments; bit ``0x08`` is set if the function uses the ``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set if the function is a generator. See :ref:`inspect-module-co-flags` for details on the semantics of each flags that might be present.
If a code object represents a function and has a docstring, the :data:`~inspect.CO_HAS_DOCSTRING` bit is set in :attr:`~codeobject.co_flags` and the first item in :attr:`~codeobject.co_consts` is the docstring of the function.
The iterator returns :class:`tuple`\s containing the ``(start_line, end_line, start_column, end_column)``. The *i-th* tuple corresponds to the position of the source code that compiled to the *i-th* code unit. Column information is 0-indexed utf-8 byte offsets on the given source line.
``start`` (an :class:`int`) represents the offset (inclusive) of the start of the :term:`bytecode` range
``end`` (an :class:`int`) represents the offset (exclusive) of the end of the :term:`bytecode` range
Set this attribute to :const:`False` to disable triggering a tracing event for each source line.
Set this attribute to :const:`True` to allow per-opcode events to be requested. Note that this may lead to undefined interpreter behaviour if exceptions raised by the trace function escape to the function being traced.
The current line number of the frame -- writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to this attribute.
Setting a special method to ``None`` indicates that the corresponding operation is not available. For example, if a class sets :meth:`~object.__iter__` to ``None``, the class is not iterable, so calling :func:`iter` on its instances will raise a :exc:`TypeError` (without falling back to :meth:`~object.__getitem__`). [#]_
:meth:`__del__` can be executed during interpreter shutdown. As a consequence, the global variables it needs to access (including other modules) may already have been deleted or set to ``None``. Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the :meth:`__del__` method is called.
Called by built-in function :func:`hash` and for operations on members of hashed collections including :class:`set`, :class:`frozenset`, :class:`dict`, and :class:`frozendict`. The ``__hash__()`` method should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. Example::
A class that overrides :meth:`__eq__` and does not define :meth:`__hash__` will have its :meth:`__hash__` implicitly set to ``None``. When the :meth:`__hash__` method of a class is ``None``, instances of the class will raise an appropriate :exc:`TypeError` when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking ``isinstance(obj, collections.abc.Hashable)``.
If a class that overrides :meth:`__eq__` needs to retain the implementation of :meth:`__hash__` from a parent class, the interpreter must be told this explicitly by setting ``__hash__ = <ParentClass>.__hash__``.
Changing hash values affects the iteration order of sets. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).
Note that if the attribute is found through the normal mechanism, :meth:`__getattr__` is not called. (This is an intentional asymmetry between :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency reasons and because otherwise :meth:`__getattr__` would have no way to access other attributes of the instance. Note that at least for instance variables, you can take total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the :meth:`__getattribute__` method below for a way to actually get total control over attribute access.
If :meth:`__setattr__` wants to assign to an instance attribute, it should call the base class method with the same name, for example, ``object.__setattr__(self, name, value)``.
For certain sensitive attribute assignments, raises an :ref:`auditing event <auditing>` ``object.__setattr__`` with arguments ``obj``, ``name``, ``value``.
Like :meth:`__setattr__` but for attribute deletion instead of assignment. This should only be implemented if ``del obj.name`` is meaningful for the object.
For a more fine grained customization of the module behavior (setting attributes, properties, etc.), one can set the ``__class__`` attribute of a module object to a subclass of :class:`types.ModuleType`. For example::
import sys from types import ModuleType class VerboseModule(ModuleType): def __repr__(self): return f'Verbose {self.__name__}' def __setattr__(self, attr, value): print(f'Setting {attr}...') super().__setattr__(attr, value) sys.modules[__name__].__class__ = VerboseModule
Defining module ``__getattr__`` and setting module ``__class__`` only affect lookups made using the attribute access syntax -- directly accessing the module globals (whether by code within the module, or via a reference to the module's globals dictionary) is unaffected.
Called to set the attribute on an instance *instance* of the owner class to a new value, *value*.
Note, adding :meth:`__set__` or :meth:`__delete__` changes the kind of descriptor to a "data descriptor". See :ref:`descriptor-invocation` for more details.
The attribute :attr:`!__objclass__` is interpreted by the :mod:`inspect` module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C).
In general, a descriptor is an object attribute with "binding behavior", one whose attribute access has been overridden by methods in the descriptor protocol: :meth:`~object.__get__`, :meth:`~object.__set__`, and :meth:`~object.__delete__`. If any of those methods are defined for an object, it is said to be a descriptor.
The default behavior for attribute access is to get, set, or delete the attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and continuing through the base classes of ``type(a)`` excluding metaclasses.
For instance bindings, the precedence of descriptor invocation depends on which descriptor methods are defined. A descriptor can define any combination of :meth:`~object.__get__`, :meth:`~object.__set__` and :meth:`~object.__delete__`. If it does not define :meth:`!__get__`, then accessing the attribute will return the descriptor object itself unless there is a value in the object's instance dictionary. If the descriptor defines :meth:`!__set__` and/or :meth:`!__delete__`, it is a data descriptor; if it defines neither, it is a non-data descriptor. Normally, data descriptors define both :meth:`!__get__` and :meth:`!__set__`, while non-data descriptors have just the :meth:`!__get__` method. Data descriptors with :meth:`!__get__` and :meth:`!__set__` (and/or :meth:`!__delete__`) defined always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by instances.
*__slots__* are implemented at the class level by creating :ref:`descriptors <descriptors>` for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by *__slots__*; otherwise, the class attribute would overwrite the descriptor assignment.
When a class is created, :meth:`!type.__new__` scans the class variables and makes callbacks to those with a :meth:`~object.__set_name__` hook.
class A: x = C() # Automatically calls: x.__set_name__(A, 'x')
If the class variable is assigned after the class is created, :meth:`__set_name__` will not be called automatically. If needed, :meth:`__set_name__` can be called directly::
class A: pass c = C() A.x = c # The hook is not called c.__set_name__(A, 'x') # Manually invoke the hook
The ``type.__new__`` method collects all of the attributes in the class namespace that define a :meth:`~object.__set_name__` method;
Those ``__set_name__`` methods are called with the class being defined and the assigned name of that particular attribute;
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`.
Slicing is handled by :meth:`!__getitem__`, :meth:`~object.__setitem__`, and :meth:`~object.__delitem__`. A call like ::
This class variable can be assigned a tuple of strings. When this class is used in a class pattern with positional arguments, each positional argument will be converted into a keyword argument, using the corresponding value in *__match_args__* as the keyword. The absence of this attribute is equivalent to setting it to ``()``.
This attribute contains the annotations for an object. It is :ref:`lazily evaluated <lazy-evaluation>`, so accessing the attribute may execute arbitrary code and raise exceptions. If evaluation is successful, the attribute is set to a dictionary mapping from variable names to annotations.
If an object does not have any annotations, :attr:`~object.__annotate__` should preferably be set to ``None`` (it can’t be deleted), rather than set to a function that returns an empty dict.
Bypassing the :meth:`~object.__getattribute__` machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method *must* be set on the class object itself in order to be consistently invoked by the interpreter).
"Does not support" here means that the class has no such method, or the method returns :data:`NotImplemented`. Do not set the method to ``None`` if you want to force fallback to the right operand's reflected method—that will instead have the opposite effect of explicitly *blocking* such fallback.
set type
set
set
frozenset