3.1. Objects, values and types¶Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.) Show
Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘ CPython implementation detail: For CPython, An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The
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. Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. CPython implementation detail: CPython currently uses a reference-counting scheme
with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the Note that the use of the implementation’s tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a
‘ Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such
objects also provide an explicit way to release the external resource, usually a 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. E.g., after 3.2. The standard type hierarchy¶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. NoneThis type has a single value. There is a single object with this value. This object is accessed through the built-in name This type has a single value. There is a single object with this value. This object is accessed through the built-in name See Implementing the arithmetic operations for more details. Changed in version 3.9: Evaluating This type has a single value. There is a single object with this value. This object is accessed through the literal numbers.Number These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers. The string representations of the numeric classes, computed by
Python distinguishes between integers, floating point numbers, and complex numbers: numbers.Integral These represent elements from the mathematical set of integers (positive and negative). There are two types of integers: Integers (int )These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left. Booleans (bool )These represent the truth values False and True. The two objects representing the values The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers. numbers.Real (float )These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. Python does not support single-precision floating point numbers; the savings in processor and memory usage that are usually the reason for using these are dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers. numbers.Complex
(complex )These represent complex numbers as a pair of machine-level double precision floating point numbers. The same caveats apply as for floating point numbers. The real and imaginary parts of a complex number These represent
finite ordered sets indexed by non-negative numbers. The built-in function Sequences also support slicing: Some sequences also support “extended slicing” with a third “step” parameter: Sequences are distinguished according to their mutability: Immutable sequencesAn object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.) The following types are immutable sequences: StringsA string is a sequence of values that represent
Unicode code points. All the code points in the range The items of a 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. BytesA bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256. Bytes literals (like Mutable sequences can be changed after they are created. The subscription and slicing notations
can be used as the target of assignment and There are currently two intrinsic mutable sequence types: ListsThe 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.) Byte ArraysA bytearray object is a mutable array. They are created by the built-in The extension module 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 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., There are currently two intrinsic set types: SetsThese represent a mutable set. They are created by the built-in
These represent an immutable set. They are created by the built-in These represent finite sets of objects indexed by arbitrary index sets. The subscript notation There is currently a single intrinsic mapping type: DictionariesThese 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., Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. Replacing an existing key does not change the order, however removing a key and re-inserting it will add it to the end instead of keeping its old place. Dictionaries are mutable; they can be created by the The
extension modules Changed in version 3.7: Dictionaries did not preserve insertion order in versions of Python before 3.6. In CPython 3.6, insertion order was preserved, but it was considered an implementation detail at that time rather than a language guarantee. Callable typesThese are the types to which the function call operation (see section Calls) can be applied: User-defined functionsA user-defined function object is created by a function definition (see section Function definitions). It should be called with an argument list containing the same number of items as the function’s formal parameter list. Special attributes:
Most of the attributes labelled “Writable” check the type of the assigned 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. Note that the current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future. A cell object has the attribute Additional information about a function’s definition can be retrieved from its code object; see the description of internal types below. The An instance method object combines a class, a class instance and any callable object (normally a user-defined function). Special read-only attributes: Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object. User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object or a class method object. When an instance method object is created by retrieving a user-defined function object from a class via one of its instances, its When an instance method object is created by retrieving a class method
object from a class or instance, its When an instance method object is called, the underlying function ( When an instance method object is derived from a class method object, the “class instance” stored in Note that the transformation from function object to instance method object happens each time the attribute is retrieved from the instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class. Generator functionsA function or method which uses the A function or method which is defined using
A function or method which is defined using
Calling the asynchronous iterator’s A built-in function object is a wrapper around a C function. Examples of built-in functions are 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 Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override Instances of arbitrary classes can be made callable by defining a Modules are a basic
organizational unit of Python code, and are created by the import system as invoked either by the Attribute assignment updates the module’s namespace dictionary, e.g., Predefined (writable) attributes:
Special read-only attribute: CPython implementation detail: Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the dictionary still has live references. To avoid this, copy the dictionary or keep the module around while using its dictionary directly. Custom classesCustom class types are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., When a class attribute reference (for class Class attribute assignments update the class’s dictionary, never the dictionary of a base class. A class object can be called (see above) to yield a class instance (see below). Special attributes: Class instances 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 Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the
class has a Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. See section Special method names. Special attributes: A file object represents an open file. Various shortcuts are available to create file objects: the The objects A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness. Code objectsCode objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects. Special read-only attributes: The following flag bits are defined for Future feature declarations ( Other bits in If a code object represents a function, the first item in Returns an iterable over the source code positions of each bytecode instruction in the code object. The iterator returns tuples containing the This positional information can be missing. A non-exhaustive lists of cases where this may happen:
When this occurs, some or all of the tuple elements can be New in version 3.11. Note This feature requires storing column positions in code objects which may result in a small increase of disk usage of compiled Python files or interpreter memory usage. To avoid storing the extra information and/or deactivate printing the extra traceback information, the Frame objects represent execution frames. They may occur in traceback objects (see below), and are also passed to registered trace functions. Special read-only attributes: Accessing Special writable attributes: Implementations may allow per-opcode events to be requested by setting
Frame objects support one method: frame.clear()¶This method clears all references to local variables held by the frame. Also, if the frame belonged to a generator, the generator is finalized. This helps break reference cycles involving frame objects (for example when catching an exception and storing its traceback for later use).
New in version 3.4. Traceback objectsTraceback objects represent a stack trace of an exception. A traceback object is implicitly created when an exception occurs, and may also be explicitly created by calling For implicitly created tracebacks, when the search for an exception handler
unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See section The try statement.) It is accessible as the third item of the tuple returned by When the program contains no
suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as For explicitly created tracebacks, it is up to the creator of the traceback to determine how the Special read-only attributes: Accessing Special writable attribute: Changed in version 3.7: Traceback objects can now be explicitly instantiated from Python code, and the Slice objects are used
to represent slices for Special read-only attributes: Slice objects support one method: slice.indices(self, length)¶This method takes a single integer argument length and computes information about the slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the start and stop indices and the step or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices. Static method objectsStatic method objects provide a way of defeating the transformation of function
objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are also callable. Static method objects are created by the built-in 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 “User-defined methods”. Class method objects are created by the built-in
3.3. Special method names¶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 operator overloading, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named Setting a special method to 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 3.3.1. Basic customization¶object.__new__(cls[, ...])¶Called to create a new instance of class cls.
Typical implementations create a new instance of the class by invoking the superclass’s If If
Called after the instance has been created (by
Because Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor. If a base class has a
It is possible (though not recommended!) for the
It is not guaranteed that Note
CPython implementation detail: It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the cyclic garbage collector. A common cause of reference cycles is when an exception has been caught in a local variable. The frame’s locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback. See also Documentation for the Warning Due to the precarious
circumstances under which
Called by the This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. object.__str__(self)¶Called by This method differs from
The default implementation defined by the built-in type
Called by bytes to compute a byte-string representation of an object. This should return a
Called by the See Format Specification Mini-Language for a description of the standard formatting syntax. The return value must be a string object. Changed in version 3.4: The __format__ method of Changed in version 3.7: These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: A rich comparison method may return the singleton By default, See the paragraph on There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, Called by built-in function def __hash__(self): return hash((self.name, self.nick, self.color)) Note
If a class does not define an User-defined
classes have A class that overrides
If a class that overrides
If a class that does not override
Note By default, the This is intended to provide protection against a denial-of-service caused by carefully chosen inputs that exploit the worst case performance of a dict insertion, O(n2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details. 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). See also Changed in version 3.3: Hash randomization is enabled by default. object.__bool__(self)¶Called to implement truth value testing and the built-in operation 3.3.2. Customizing attribute access¶The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of Called when the default attribute access fails with an Note that if the attribute is found through the normal mechanism, Called unconditionally to implement attribute accesses for instances of the class. If the class also defines
Note This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions. See Special method lookup. For certain sensitive attribute accesses, raises an auditing event Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). name is the attribute name, value is the value to be assigned to it. If For certain sensitive attribute assignments, raises an
auditing event Like For certain sensitive
attribute deletions, raises an auditing event Called when 3.3.2.1. Customizing module attribute access¶Special names The For a more fine grained customization of the module behavior (setting attributes, properties, etc.), one can set the 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 Note Defining module Changed in version 3.5: New in version 3.7: See also PEP 562 - Module __getattr__ and __dir__Describes
the 3.3.2.2. Implementing Descriptors¶The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner
class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents). In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ Called to get the attribute of the owner class (class attribute access) or of
an instance of that class (instance attribute access). The optional owner argument is the owner class, while instance is the instance that the attribute was accessed through, or This method should return the computed attribute value or raise an PEP 252 specifies that Called to set the attribute on an instance instance of the owner class to a new value, value. Note, adding Called to delete the attribute on an instance instance of the owner class. The attribute 3.3.2.3. Invoking Descriptors¶In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol:
The default
behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined and how they were called. The starting point for descriptor invocation is a binding, The simplest and least common call is when user code directly invokes a descriptor method: If binding to an object instance, If binding to a
class, A dotted lookup such as For instance bindings, the precedence of descriptor invocation depends on which descriptor methods are defined. A descriptor can define any combination of
Python methods (including those decorated with The 3.3.2.4. __slots__¶__slots__ allow
us to explicitly declare data members (like properties) and deny the creation of The space saved over using This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __slots__ reserves space for the declared variables and prevents the
automatic creation of 3.3.2.4.1. Notes on using __slots__¶
3.3.3. Customizing class creation¶Whenever a class inherits from another class,
This method is called whenever the containing class is subclassed. cls is then the new subclass. If defined as a normal instance method, this method is implicitly converted to a class method. Keyword arguments which are given to a new class are passed to the parent’s class class Philosopher: def __init_subclass__(cls, /, default_name, **kwargs): super().__init_subclass__(**kwargs) cls.default_name = default_name class AustralianPhilosopher(Philosopher, default_name="Bruce"): pass The default implementation Note The metaclass hint
New in version 3.6. When a class is created, Automatically called at the time the owning class owner is created. The object has been assigned to name in that class: class A: x = C() # Automatically calls: x.__set_name__(A, 'x') If the class variable is assigned after the class is created, class A: pass c = C() A.x = c # The hook is not called c.__set_name__(A, 'x') # Manually invoke the hook See Creating the class object for more details. New in version 3.6. 3.3.3.1. Metaclasses¶By default, classes are constructed using
The class creation process can be customized by passing the class Meta(type): pass class MyClass(metaclass=Meta): pass class MySubclass(MyClass): pass Any other keyword arguments that are specified in the class definition are passed through to all metaclass operations described below. When a class definition is executed, the following steps occur:
3.3.3.2. Resolving MRO entries¶If a base that appears in class definition is not an instance of See also PEP 560 - Core support for typing module and generic types 3.3.3.3. Determining the appropriate metaclass¶The appropriate metaclass for a class definition is determined as follows:
The most derived metaclass is selected from the explicitly
specified metaclass (if any) and the metaclasses (i.e. 3.3.3.4. Preparing the class namespace¶Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a If the metaclass has no See also PEP 3115 - Metaclasses in Python 3000Introduced the 3.3.3.5. Executing the class body¶The class body is executed
(approximately) as However, even when the class definition occurs inside the function, methods defined inside the class still cannot see names defined at the
class scope. Class variables must be accessed through the first parameter of instance or class methods, or through the implicit lexically scoped 3.3.3.6. Creating the class object¶Once the class namespace has been populated by executing the class body, the class object is created by calling This class object is the one that will be referenced by the zero-argument form of CPython implementation detail: In CPython 3.6 and later, the When using the default metaclass
After the class object is created, it is passed to the class decorators included in the class definition (if any) and the resulting object is bound in the local namespace as the defined class. When a
new class is created by See also PEP 3135 - New superDescribes the implicit 3.3.3.7. 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. 3.3.4. Customizing instance and subclass checks¶The
following methods are used to override the default behavior of the In particular, the metaclass Return true if instance should be considered a (direct or indirect) instance of class. If defined, called to implement Return true if subclass should be considered a (direct or indirect) subclass of class. If defined, called to implement Note that these methods are looked up on the type (metaclass) of a class. They cannot be defined as class methods in the actual class. This is consistent with the lookup of special methods that are called on instances, only in this case the instance is itself a class. 3.3.5. Emulating generic types¶When using type annotations, it is often useful to parameterize a generic type using Python’s square-brackets notation. For example, the
annotation See also PEP 484 - Type HintsIntroducing Python’s framework for type annotations Generic Alias TypesDocumentation for objects representing parameterized generic classes Generics, user-defined generics andtyping.Generic Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers. A class can generally only be parameterized if it defines the special class method Return an object representing the specialization of a generic class by type arguments found in key. When defined on a class, 3.3.5.1. The purpose of __class_getitem__¶The purpose of 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 Custom implementations of
3.3.5.2. __class_getitem__ versus __getitem__¶Usually, the subscription of an object using square brackets will call the
Presented with the expression from inspect import isclass def subscribe(obj, x): """Return the result of the expression 'obj[x]'""" class_of_obj = type(obj) # If the class of obj defines __getitem__, # call class_of_obj.__getitem__(obj, x) if hasattr(class_of_obj, '__getitem__'): return class_of_obj.__getitem__(obj, x) # Else, if obj is a class and defines __class_getitem__, # call obj.__class_getitem__(x) elif isclass(obj) and hasattr(obj, '__class_getitem__'): return obj.__class_getitem__(x) # Else, raise an exception else: raise TypeError( f"'{class_of_obj.__name__}' object is not subscriptable" ) In Python, all classes are themselves instances of other classes. The class of a class is known as that class’s
metaclass, and most classes have the >>> # 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'> However, if a class has a custom metaclass that defines
>>> 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'> 3.3.6. Emulating callable objects¶object.__call__(self[, args...])¶Called when the instance is “called” as a function; if this method is defined, 3.3.7. Emulating container types¶The following methods can be defined to implement container objects. Containers usually are sequences (such as Called to implement the built-in function CPython implementation detail: In CPython, the length is required to be at most
Called to
implement New in version 3.4. Note Slicing is done exclusively with the following three methods. A call like is translated to and so forth. Missing slice items are always filled in with Called to implement evaluation of Note
Called to implement assignment to
Called to implement deletion of Called by This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container. object.__reversed__(self)¶Called (if present) by the If the The membership test operators ( Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs. For objects that don’t define
3.3.8. Emulating numeric types¶The following methods can be defined to emulate numeric objects. Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined. object.__add__(self, other)¶ object.__sub__(self, other)¶ object.__mul__(self, other)¶ object.__matmul__(self, other)¶ object.__truediv__(self, other)¶ object.__floordiv__(self, other)¶ object.__mod__(self, other)¶ object.__divmod__(self, other)¶ object.__pow__(self, other[, modulo])¶ object.__lshift__(self, other)¶ object.__rshift__(self, other)¶ object.__and__(self, other)¶ object.__xor__(self, other)¶ object.__or__(self, other)¶These methods are called to implement the binary arithmetic operations ( If one of those methods does not support the operation with the supplied arguments, it should return These methods are called to implement the binary arithmetic operations ( Note that ternary
Note 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. object.__iadd__(self, other)¶ object.__isub__(self, other)¶ object.__imul__(self, other)¶ object.__imatmul__(self, other)¶ object.__itruediv__(self, other)¶ object.__ifloordiv__(self, other)¶ object.__imod__(self, other)¶ object.__ipow__(self, other[, modulo])¶ object.__ilshift__(self, other)¶ object.__irshift__(self, other)¶ object.__iand__(self, other)¶ object.__ixor__(self, other)¶ object.__ior__(self, other)¶These methods are called to implement the augmented arithmetic assignments ( Called to implement the unary arithmetic operations ( Called to implement the built-in functions Called to implement If
Called to implement the built-in function The built-in function Changed in version 3.11: The delegation of
3.3.9. With Statement Context Managers¶A context manager is an object that defines the runtime context to be established when executing a Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc. For more information on context managers, see Context Manager Types. object.__enter__(self)¶Enter the runtime context related to
this object. The Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be
If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method. Note that
See also PEP 343 - The “with” statementThe specification, background, and examples for the Python
3.3.10. Customizing positional arguments in class pattern matching¶When using a class name in a pattern, positional arguments in the pattern are not allowed by default, i.e. 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 For example, if New in version 3.10. See also PEP 634 - Structural Pattern MatchingThe specification for the Python 3.3.11. Special method lookup¶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: >>> class C: ... pass ... >>> c = C() >>> c.__len__ = lambda: 5 >>> len(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'C' has no len() The rationale behind this behaviour lies with a number of special methods such
as >>> 1 .__hash__() == hash(1) True >>> int.__hash__() == hash(int) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: descriptor '__hash__' of 'int' object needs an argument Incorrectly attempting to invoke an unbound method of a class in this way is sometimes referred to as ‘metaclass confusion’, and is avoided by bypassing the instance when looking up special methods: >>> type(1).__hash__(1) == hash(1) True >>> type(int).__hash__(int) == hash(int) True In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the >>> class Meta(type): ... def __getattribute__(*args): ... print("Metaclass getattribute invoked") ... return type.__getattribute__(*args) ... >>> class C(object, metaclass=Meta): ... def __len__(self): ... return 10 ... def __getattribute__(*args): ... print("Class getattribute invoked") ... return object.__getattribute__(*args) ... >>> c = C() >>> c.__len__() # Explicit lookup via instance Class getattribute invoked 10 >>> type(c).__len__(c) # Explicit lookup via type Metaclass getattribute invoked 10 >>> len(c) # Implicit lookup 10 Bypassing the 3.4. Coroutines¶3.4.1. Awaitable Objects¶An
awaitable object generally implements an Must return an
iterator. Should be used to implement awaitable objects. For instance, New in version 3.5. See also PEP 492 for additional information about awaitable objects. 3.4.2. Coroutine Objects¶Coroutine objects are awaitable objects. A coroutine’s execution can be controlled by calling
Coroutines also have the methods listed below, which are analogous to those of generators (see Generator-iterator methods). However, unlike generators, coroutines do not directly support iteration. Changed in version 3.5.2: It is a Starts or resumes execution of the coroutine. If value is Raises the specified exception in the coroutine. This method delegates to the Causes the coroutine to clean itself up and exit. If the coroutine is suspended, this method first delegates to the Coroutine objects are automatically closed using the above process when they are about to be destroyed. 3.4.3. Asynchronous Iterators¶An asynchronous iterator can call asynchronous code in its Asynchronous iterators can be used in an
Must return an asynchronous iterator object. object.__anext__(self)¶Must return an awaitable resulting in a next value of the iterator. Should raise a
An example of an asynchronous iterable object: class Reader: async def readline(self): ... def __aiter__(self): return self async def __anext__(self): val = await self.readline() if val == b'': raise StopAsyncIteration return val New in version 3.5. Changed in version 3.7: Prior to Python 3.7, Starting with Python 3.7, 3.4.4. Asynchronous Context Managers¶An asynchronous context manager is a context
manager that is able to suspend execution in its Asynchronous context managers can be used in an Semantically similar to Semantically
similar to An example of an asynchronous context manager class: class AsyncContextManager: async def __aenter__(self): await log('entering context') async def __aexit__(self, exc_type, exc, tb): await log('exiting context') New in version 3.5. Footnotes 1It is possible in some cases to change an object’s type, under certain controlled conditions. It generally isn’t a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly. 2The “Does not support” here means that the class has no such method, or the method returns For operands of the same type, it is assumed that if the non-reflected method – such as What data types can store a value in the least amount of memory?The data type that can store the value 0 using least amount of memory is “ Byte ”. Hence, the correct answer is option “ D ”.
What method sets or updates values of instance variable when creating a class to protect data?Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value.
What is the term used to refer to the data passed into the methods?Definition clarification: What is passed "to" a method is referred to as an "argument". The "type" of data that a method can receive is referred to as a "parameter". (You may see "arguments" referred to as "actual parameters" and "parameters" referred to as "formal parameters".)
What is the meaning of instance variable?An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class.
|