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
The string representations of the numeric classes, computed by :meth:`~object.__repr__` and :meth:`~object.__str__`, have the following properties:
Classes
Classes
Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override :meth:`~object.__new__`. The arguments of the call are passed to :meth:`!__new__` and, in the typical case, to :meth:`~object.__init__` to initialize the new instance.
Instances of arbitrary classes can be made callable by defining a :meth:`~object.__call__` method in their class.
Custom classes
Custom class types are typically created by class definitions (see section :ref:`class`). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., ``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of 'diamond' inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found at :ref:`python_2.3_mro`.
The class's documentation string, or ``None`` if undefined. Not inherited by subclasses.
Accessing the :attr:`!__annotations__` attribute directly on a class object may return annotations for the wrong class, specifically in certain cases where the class, its base class, or a metaclass is defined under ``from __future__ import annotations``. See :pep:`749 <749#pep749-metaclasses>` for details.
This attribute does not exist on certain builtin classes. On user-defined classes without ``__annotations__``, it is an empty dictionary.
A :class:`tuple` containing the :ref:`type parameters <type-params>` of a :ref:`generic class <generic-classes>`.
The :class:`tuple` of classes that are considered when looking for base classes during method resolution.
In addition to the special attributes described above, all Python classes also have the following two methods available:
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:
>>> class A: pass >>> class B(A): pass >>> A.__subclasses__() [<class 'B'>]
A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance's class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user-defined function object, it is transformed into an instance method object whose :attr:`~method.__self__` attribute is the instance. Static method and class method objects are also transformed; see above under "Classes". See section :ref:`descriptors` for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class's :attr:`~object.__dict__`. If no class attribute is found, and the object's class has a :meth:`~object.__getattr__` method, that is called to satisfy the lookup.
A class method object, like a static method object, is a wrapper around another object that alters the way in which that object is retrieved from classes and class instances. The behaviour of class method objects upon such retrieval is described above, under :ref:`"instance methods" <instance-methods>`. Class method objects are created by the built-in :func:`classmethod` constructor.
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python's approach to :dfn:`operator overloading`, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named :meth:`~object.__getitem__`, and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically :exc:`AttributeError` or :exc:`TypeError`).
:meth:`__new__` is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
Called by the :func:`format` built-in function, and by extension, evaluation of :ref:`formatted string literals <f-strings>` and the :meth:`str.format` method, to produce a "formatted" string representation of an object. The *format_spec* argument is a string that contains a description of the formatting options desired. The interpretation of the *format_spec* argument is up to the type implementing :meth:`__format__`, however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.
User-defined classes have :meth:`__eq__` and :meth:`__hash__` methods by default (inherited from the :class:`object` class); with them, all objects compare unequal (except with themselves) and ``x.__hash__()`` returns an appropriate value such that ``x == y`` implies both that ``x is y`` and ``hash(x) == hash(y)``.
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.
Without a *__weakref__* variable for each instance, classes defining *__slots__* do not support :mod:`weak references <weakref>` to its instances. If weak reference support is needed, then add ``'__weakref__'`` to the sequence of strings in the *__slots__* declaration.
The action of a *__slots__* declaration is not limited to the class where it is defined. *__slots__* declared in parents are available in child classes. However, instances of a child subclass will get a :attr:`~object.__dict__` and *__weakref__* unless the subclass also defines *__slots__* (which should only contain names of any *additional* slots).
:attr:`~object.__class__` assignment works only if both classes have the same *__slots__*.
:ref:`Multiple inheritance <multiple-inheritance>` with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise :exc:`TypeError`.
Whenever a class inherits from another class, :meth:`~object.__init_subclass__` is called on the parent class. This way, it is possible to write classes which change the behavior of subclasses. This is closely related to class decorators, but where class decorators only affect the specific class they're applied to, ``__init_subclass__`` solely applies to future subclasses of the class defining the method.
Keyword arguments which are given to a new class are passed to the parent class's ``__init_subclass__``. For compatibility with other classes using ``__init_subclass__``, one should take out the needed keyword arguments and pass the others over to the base class, as in::
Metaclasses
By default, classes are constructed using :func:`type`. The class body is executed in a new namespace and the class name is bound locally to the result of ``type(name, bases, namespace)``.
If a base that appears in a class definition is not an instance of :class:`type`, then an :meth:`!__mro_entries__` method is searched on the base. If an :meth:`!__mro_entries__` method is found, the base is substituted with the result of a call to :meth:`!__mro_entries__` when creating the class. The method is called with the original bases tuple passed to the *bases* parameter, and must return a tuple of classes that will be used instead of the base. The returned tuple may be empty: in these cases, the original base is ignored.
The most derived metaclass is selected from the explicitly specified metaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all specified base classes. The most derived metaclass is one which is a subtype of *all* of these candidate metaclasses. If none of the candidate metaclasses meets that criterion, then the class definition will fail with ``TypeError``.
:pep:`3115` - Metaclasses in Python 3000
Uses for metaclasses
The potential uses for metaclasses are boundless. Some ideas that have been explored include enum, logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.
In particular, the metaclass :class:`abc.ABCMeta` implements these methods in order to allow the addition of Abstract Base Classes (ABCs) as "virtual base classes" to any class or type (including built-in types), including other ABCs.
:pep:`3119` - Introducing Abstract Base Classes
Includes the specification for customizing :func:`isinstance` and :func:`issubclass` behavior through :meth:`~type.__instancecheck__` and :meth:`~type.__subclasscheck__`, with motivation for this functionality in the context of adding Abstract Base Classes (see the :mod:`abc` module) to the language.
Documentation for objects representing parameterized generic classes
Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.
The purpose of :meth:`~object.__class_getitem__` is to allow runtime parameterization of standard-library generic classes in order to more easily apply :term:`type hints<type hint>` to these classes.
To implement custom generic classes that can be parameterized at runtime and understood by static type-checkers, users should either inherit from a standard library class that already implements :meth:`~object.__class_getitem__`, or inherit from :class:`typing.Generic`, which has its own implementation of ``__class_getitem__()``.
Custom implementations of :meth:`~object.__class_getitem__` on classes defined outside of the standard library may not be understood by third-party type-checkers such as mypy. Using ``__class_getitem__()`` on any class for purposes other than type hinting is discouraged.
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'>
>>> from enum import Enum >>> class Menu(Enum): ... """A breakfast menu""" ... SPAM = 'spam' ... BACON = 'bacon' ... >>> # Enum classes have a custom metaclass: >>> type(Menu) <class 'enum.EnumMeta'> >>> # EnumMeta defines __getitem__, >>> # so __class_getitem__ is not called, >>> # and the result is not a GenericAlias object: >>> Menu['SPAM'] <Menu.SPAM: 'spam'> >>> type(Menu['SPAM']) <enum 'Menu'>
If *subscript* is of an inappropriate type, :meth:`!__getitem__` should raise :exc:`TypeError`. If *subscript* has an inappropriate value, :meth:`!__getitem__` should raise an :exc:`LookupError` or one of its subclasses (:exc:`IndexError` for sequences; :exc:`KeyError` for mappings).
Called by :class:`dict`\ .\ :meth:`__getitem__` to implement ``self[key]`` for dict subclasses when key is not in the dictionary.
If the right operand's type is a subclass of the left operand's type and that subclass provides a different implementation of the reflected method for the operation, this method will be called before the left operand's non-reflected method. This behavior allows subclasses to override their ancestors' operations.
Functions, classes, and modules may contain :term:`annotations <annotation>`, which are a way to associate information (usually :term:`type hints <type hint>`) with a symbol.
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object's type, not in the object's instance dictionary. That behaviour is the reason why the following code raises an exception::
If the right operand's type is a subclass of the left operand's type, the reflected method having precedence allows subclasses to override their ancestors' operations.