Specials

Contents

Specials#

The specials is a group of methods/attributes that have a special meaning for Python. They are wrapped double underscores, for example, __init__. Alternative names are magics and dunders (a shortcut for double underscore before and after).

Methods#

In classes, a set of methods with reserved names can be implemented. These methods are called when specific events occur with the class or its instances. Names of all this methods follows such pattern __<name>__, for example __init__, __repr__ and so on.

Find out more in the:

The following table shows some special methods and their descriptions.

Group

Method

Description

Object management

__new__(cls)

Static method called to create a new instance

__init__(self)

Called immediately after instance creation

__del__(self)

Called when the instance is about to be destroyed - the correct abstract way to name it is “finalizer”

Type Conversion

__str__(self)

Defines how an object should be converted into a string datatype.

__bool__(self)

Defines how an object should be converted into a boolean datatype.

__int__(self)

Defines how an object should be converted into an integer datatype.

__float__(self)

Defines how an object should be converted into a float datatype.

__complex__(self)

Defines how an object should be converted into a complex datatype.

Arithmetic operators

__eq__(self, other)

Compares two objects for equality (==).

__lt__(self, other)

Compares if the object is less than another (<).

__le__(self, other)

Compares if the object is less than or equal to another (<=).

__gt__(self, other)

Compares if the object is greater than another (>).

__ge__(self, other)

Compares if the object is greater than or equal to another (>=).

__add__(self, other)

Defines addition for objects (+).

__sub__(self, other)

Defines subtraction for objects (-).

__mul__(self, other)

Defines multiplication for objects (*).

__truediv__(self, other)

Defines division for objects (/).

__floordiv__(self, other)

Defines floor division for objects (//).

__mod__(self, other)

Defines modulo operation for objects (%).

__pow__(self, other)

Defines power operation for objects (**).

__and__(self, other)

Defines bitwise AND operation (&).

__or__(self, other)

Defines bitwise OR operation (`

__xor__(self, other)

Defines bitwise XOR operation (^).

__iadd__(self, other)

Defines in-place addition (+=).

__isub__(self, other)

Defines in-place subtraction (-=).

__imul__(self, other)

Defines in-place multiplication (*=).

__idiv__(self, other)

Defines in-place division (/=).

__neg__(self)

Defines unary negation (-).

__abs__(self)

Returns the absolute value of the object (abs()).

Indexing operator ([])

__setitem__(self, key, value)

To try assigning a value to the index.

__getitem__(self, key)

To try to access value under the index.

__delitem__(self, key)

To try to delete value under the index

Iteration protocol

__iter__(self)

Will be called each time you need iterate over object.

__next__(self)

Will be called each time the object is passed to the next build in function.

Customizing class creation

__init_subclass__(cls)

This method is called when ever the containing class is subclassed.


As an example, consider a class that has the __getitem__ method defined. This method determines the behavior of the instances of the class when the [] operator is applied to them.

Here is how it works — it converts the literal 3 to the type of the input and applies + to the input and the transformed literal 3.

class TestClass:
    def __getitem__(self, item):
        return item + type(item)(3)

The following cell shows the behavior of the instance when 9 is passed to the [] operator.

TestClass()[6]
9

You can pass string literals as well.

TestClass()["hello"]
'hello3'

Attributes#

Actually, almost every instance in the Python environment has its own special attributes, but they come from different abstractions of the language:

  • Type attributes: Attributes of the type itself. The type class, like int, holds these attributes.

  • Function attributes, Method attributes: Their purpose is clear from their names.

  • Instance attributes: Attributes that appear in an instance during its creation.

Category

Attribute

Description

Type Attributes

__name__

Name of the class.

__module__

Module where the class is defined.

__dict__

Dictionary containing the class’s attributes and methods.

__bases__

Tuple of base classes (superclasses).

__mro__

Method Resolution Order (tuple of base classes in order).

__subclasses__()

Returns a list of known subclasses.

__doc__

Docstring of the class (or None if not defined).

__annotations__

Dictionary of variable type annotations.

__qualname__

Fully qualified class name (e.g., Outer.Inner).

Function Attributes

__code__

Code object representing the function’s compiled bytecode.

__defaults__

Tuple of default values for function parameters.

__kwdefaults__

Dictionary of default values for keyword-only arguments.

__globals__

Reference to the global namespace where the function is defined.

__closure__

Tuple of cell objects containing variables used in closures.

__annotations__

Dictionary of function parameter and return type annotations.

Method Attributes

__func__

Reference to the underlying function of a method.

__self__

Instance to which a bound method is attached.

__doc__

Docstring of the method.

__annotations__

Dictionary of method parameter and return type annotations.

Instance Attributes

__dict__

Dictionary containing instance attributes.

__class__

Reference to the class of the instance.

__slots__

Tuple defining allowed instance attributes (if used).

__weakref__

List of weak references to the object (if applicable).

Check more specific description at the corresponding page.