Classes intercept and implement built-in operations by providing specially named method functions, all of which start and end with two underscores. These names are not reserved and can be inherited from superclasses as usual. Python locates and calls at most one per operation.
Python automatically calls a class’s overloading methods when
instances appear in expressions and other contexts. For example, if a
class defines a method named __getitem__
, and X
is an instance of this class, the expression
X[i]
is equivalent to the method call
X.__getitem__(i)
.
Overloading method names are sometimes arbitrary: a class’s
__add__
method need not perform an
addition (or concatenation). Moreover, classes generally can mix numeric
and collection methods and mutable and immutable operations. Most
operator overloading names have no defaults, and the corresponding
operation raises an exception if its method is not defined.
__new__(cls [,
args...])
Called to create and return a new instance of
class cls
. Receives
constructor arguments passed to the class. If this returns an
instance of the class, the instance’s __init__
method is invoked with the same constructor arguments.
Not used in normal classes; intended to allow subclasses of
immutable types to customize instance creation, and to allow
custom metaclasses to customize class creation.
__init__(self [,
arg]*)
Invoked on class(args...)
. This is the
constructor that initializes the new instance, self
. When run for calls to a class
name, self
is provided
automatically; arg
is the
arguments passed to the
class name, and may be any function-definition argument form
(see The Expression Statement and The def Statement). Must return no value, and call
superclass __init__
manually
if needed, passing the instance to self
.
__del__(self)
Invoked on instance garbage collection. This destructor
method cleans up when an instance is freed. Embedded objects are
automatically freed when the parent is (unless referenced from
elsewhere). Exceptions during this method’s run are ignored, and
simply print messages to sys.stderr
. The try
/finally
statement allows more
predictable termination actions for a code block.
__repr__(self)
Invoked on repr(self)
,
and interactive echoes, (and `self`
in Python 2.X only). Also
invoked on str(self)
and
print(self)
if there is no
__str__
. This method returns
a low-level “as code” string representation of self
.
__str__(self)
Invoked on str(self)
and print(self)
(or uses
__repr__
as a backup if
defined). This method returns a high-level “user friendly”
string representation of self
.
__format__(self,
formatspec)
Called by the format()
built-in function (and by extension, the str.format()
method of str
strings) to produce a “formatted”
string representation of an object. See Strings and Built-in Functions.
New in Python 2.6 and 3.0.
__hash__(self)
Invoked on dictionary[self]
and hash(self)
, and other hashed
collection operations, including those of the set object type.
This method returns a unique and unchanging integer
hash-key.
__bool__(self)
Called for truth value testing and the built-in bool()
function; returns False
or True
. When __bool__()
is not defined, __len__()
is called if it is defined
and designates a true value with a nonzero length. If neither
__len__()
nor __bool__()
is defined, all its
instances are considered true. New in Python 3.0; in Python 2.X,
this method is named __nonzero__
instead of __bool__
, but works the same
way.
__call__(self [,
arg]*)
Invoked on self(args...)
, when an instance is
called like a function. arg
may take any function-definition argument form (see The Expression Statement and The def Statement). For example, __call__(self, a, b, c, d=5)
and
__call__(self, *pargs,
**kargs)
both match calls self(1, 2, 3, 4)
and self(1, *(2,), c=3,
**dict(d=4))
.
__getattr__(self,
name)
Invoked on self.name
,
when name
is an undefined
attribute access (this method is not called if name
exists in or is inherited by
self
). name
is a string. This method returns
an object or raises AttributeError
.
In Python 3.0, this is no longer run for __X__
attributes implicitly fetched by
built-in operations; redefine such names in wrapper/proxy
classes.
__setattr__(self, name,
value)
Invoked on self.name=value
(all attribute
assignments). Hint—assign through __dict__
key to avoid recursive loops:
self.attr=x
statement within
a __setattr__
calls __setattr__
again, but self.__dict__['attr']=x
does not.
Recursion may also be avoided by calling the superclass version
explicitly: object.__setattr__(self,
name, value)
.
__delattr__(self,
name)
Invoked on del
self.name
(all attribute deletions). Hint: must avoid
recursive loops by routing attribute deletions through __dict__
or a superclass, much like
__setattr__
.
__getattribute__(self,
name)
Called unconditionally to implement attribute accesses for
instances of the class. If the class also defines __getattr__
, it
will never be called (unless it is called explicitly). This
method should return the (computed) attribute value or raise an
AttributeError
exception. To
avoid infinite recursion in this method, its implementation
should always call the superclass method with the same name to
access any attributes it
needs (e.g., object.__getattribute__(self,
name)
.
In Python 3.0, this is no longer run for __
X
__
attributes implicitly fetched by
built-in operations; redefine such names in wrapper/proxy
classes.
__lt__(self,
other)
__le__(self,
other)
__eq__(self,
other)
__ne__(self,
other)
__gt__(self,
other)
__ge__(self,
other)
Respectively, used on self <
other
, self <=
other
, self ==
other
, self !=
other
, and self >
other
, self >=
other
. Added in version 2.1, these are known as
rich comparison methods and
are called for all comparison expressions in Python 3.0. For
example, X < Y
calls
X.__lt__(Y)
if defined. In
Python 2.X only, these methods are called in preference to
__cmp__
, and __ne__
is also run for self <> other
.
These methods can return any value, but if the comparison
operator is used in a Boolean context, the return value is
interpreted as a Boolean result for the operator. These methods
can also return (not raise) the special object NotImplemented
if not supported for
the operands (which works as though the method were not defined
at all, and which forces Python 2.X to revert to the general
__cmp__
method if
defined).
There are no implied relationships among comparison
operators. For example, x==y
being true does not imply that x!=y
is false: __ne__
should be defined along with
__eq__
if the operators are
expected to behave symmetrically. There are also no right-side
(swapped-argument) versions of these methods to be used when the
left argument does not support the operation but the right
argument does. __lt__
and
__gt__
are each other’s
reflection, __le__
and
__ge__
are each other’s
reflection, and __eq__
and
__ne__
are their own
reflections. Use __lt__
for
sorting in Python 3.0.
__slots__
This class attribute can be assigned a string, iterable,
or sequence of strings giving the names of attributes of
instances of the class. If defined in a new-style class
(including all classes in Python 3), __slots__
reserves space for the
declared attributes, and prevents the automatic creation of
__dict__
for each instance
(unless string '__dict__'
is
included in __slots__
, in
which case instances also have a __dict__
and attributes not named in
__slots__
may be added
dynamically).
To support classes with __slots__
, tools that generically list
attributes or access them by string name must use storage-neutral tools such as the
getattr()
, setattr()
, and dir()
, which apply to both __dict__
and __slots__
attribute storage. Both
attribute sources may need to be queried.
__dir__(self)
Called on dir(self)
.
Returns a list of attribute names. New in Python 3.0.
__len__(self)
Invoked on len(self)
and possibly for truth-value tests. This method returns a
collection’s size. For Boolean tests, Python looks for __bool__
first, then __len__
, and then considers the object
true (__bool__
is named
__nonzero__
in Python 2). Zero
length means false.
__contains__(self,
item)
Invoked on item in self
for custom membership tests (otherwise, membership uses __iter__
, if defined, or __getitem__
). This method returns a
true or false result.
__iter__(self)
Invoked on iter(self)
.
New in version 2.2, this method is part of the iteration
protocol. It returns an object with a __next__()
method (possibly self
). The result object’s __next__()
method is then called
repeatedly in all iteration contexts (e.g., for
loops), and should return the
next result or raise
StopIteration
to terminate
the results progression.
See also sections The for Statement and The yield Statement. If no __iter__
is defined, iteration falls
back on __getitem__
. In
Python 2.X, __next__()
is
named next()
.
__next__(self)
Invoked by the next(self)
built-in function, and by
all iteration contexts to advance through results. See __iter__()
for usage details. New in
Python 3.0; in Python 2.X, this method is named next()
, but works the same way.
__getitem__(self,
key)
Invoked on self[key]
,
self[i:j:k]
, x in self
, and for x in self
(and all iteration
contexts). This method implements all indexing-related
operations. Iteration contexts (e.g., in
and for
) repeatedly index from 0 until
IndexError
, unless __iter__
is defined.
In Python 3.0, this and the following two methods are also
called for slice operations, in which case key
is a slice object. Slice objects
may be propagated to another slice expression, and have
attributes start
, stop
, and step
, any of which can be None
. See also slice()
in Built-in Functions.
__setitem__(self, key,
value)
Invoked on self[key]=value
, self[i:j:k]=value
. This method is
called for assignment to a collection key or index, or to a
sequence’s slice.
__delitem__(self,
key)
Invoked on del
self[key]
, del
self[i:j:k]
. This method called is for index/key and
sequence slice deletion.
__reversed__(self)
Called if defined by the reversed()
built-in function to
implement custom reverse iteration. Returns a new iterator
object that iterates over all the objects in the container in
reverse order. If no __reversed__
is defined, reversed()
expects and uses sequence
protocol (methods __len__()
and __getitem__()
).
If one of those methods does not support the operation with the supplied arguments,
it should return (not raise) the built-in NotImplemented
object (which works as though
the method were not defined at all).
__add__(self,
other)
Invoked on self +
other
for numeric addition or sequence
concatenation.
__sub__(self,
other)
Invoked on self -
other
.
__mul__(self,
other)
Invoked on self *
other
for numeric multiplication or sequence
repetition.
__truediv__(self,
other)
Invoked on self /
other
for all division (which retains remainders) in
Python 3.0. In Python 2.X only, __div__
is called for classic
division (where integer division truncates).
__floordiv__(self,
other)
Invoked on self //
other
for truncating (always) division.
__mod__(self,
other)
Invoked on self %
other
.
__divmod__(self,
other)
Invoked on divmod(self,
other)
.
__pow__(self, other [,
modulo])
Invoked on pow(self, other [,
modulo])
and self **
other
.
__lshift__(self,
other)
Invoked on self <<
other
.
__rshift__(self,
other)
Invoked on self >>
other
.
__and__(self,
other)
Invoked on self &
other
.
__xor__(self,
other)
Invoked on self ^
other
.
__or__(self,
other)
Invoked on self |
other
.
__radd__(self,
other)
__rsub__(self,
other)
__rmul__(self,
other)
__rtruediv__(self,
other)
__rfloordiv__(self,
other)
__rmod__(self,
other)
__rdivmod__(self,
other)
__rpow__(self,
other)
__rlshift__(self,
other)
__rrshift__(self,
other)
__rand__(self,
other)
__rxor__(self,
other)
__ror__(self,
other)
These are right-side counterparts to the binary
operators of the prior section. Binary operator methods have a
right-side variant that starts with an r
prefix (e.g., __add__
and __radd__
). Right-side variants have
the same argument lists, but self
is on the right side of the
operator. For instance, self +
other
calls self.__add__(other)
, but other + self
invokes self.__radd__(other)
.
The r
right-side
method is called only when the instance is on the right and
the left operand is not an instance of a class that implements
the operation:
instance + noninstance runs __add__ |
instance + instance runs __add__ |
noninstance + instance runs __radd__ |
If two different class instances that overload the
operation appear, the class on the left is preferred. __radd__
often converts or swaps
order and re-adds to trigger __add__
.
__iadd__(self,
other)
__isub__(self,
other)
__imul__(self,
other)
__itruediv__(self,
other)
__ifloordiv__(self,
other)
__imod__(self,
other)
__ipow__(self, other[,
modulo])
__ilshift__(self,
other)
__irshift__(self,
other)
__iand__(self,
other)
__ixor__(self,
other)
__ior__(self,
other)
These are augmented assignment (in-place) methods.
Respectively, they are called for the following assignment
statement formats: +=
,
-=
, *=
, /=
, //=
, %=
, **=
, <<=
, >>=
, &=
, ^=
, and |=
. These methods should attempt to
do the operation in-place (modifying self
) and return the result (which
can be self
). If a method
is not defined, then the augmented operation falls back on the
normal methods. To evaluate X +=
Y
, where X
is an
instance of a class that has an __iadd__
, x.__iadd__(y)
is called. Otherwise,
__add__
and __radd__
are considered.
__neg__(self)
Invoked on -self
.
__pos__(self)
Invoked on +self
.
__abs__(self)
Invoked on abs(self)
.
__invert__(self)
Invoked on ˜self
.
__complex__(self)
Invoked on complex(self)
.
__int__(self)
Invoked on int(self)
.
__float__(self)
Invoked on float(self)
.
__round__(self [,
n])
Invoked on round(self [,
n])
. New in Python 3.0.
__index__(self)
Called to implement operator.index()
. Also called in other contexts where Python
requires an integer object. This includes instance appearances
as indexes, as slice bounds, and as arguments to the built-in
bin()
, hex()
, and oct()
functions. Must return an
integer.
Similar in Python 3.0 and 2.6, but not called for hex()
and oct()
in 2.6 (these require __hex__
and __oct__
methods in 2.6). In Python
3.0, __index__
subsumes and
replaces the __oct__
and
__hex__
methods of Python
2.X, and the returned integer is formatted automatically.
The following methods apply only when an instance of a class defining the method (a descriptor class) is assigned to a class attribute of another class (known as the owner class). These methods are invoked for access to the attribute in the owner class whose name is assigned to the descriptor class instance.
__get__(self, instance,
owner)
Called to get the attribute of the owner class or of an
instance of that class. owner
is always the owner class; instance
is the instance the attribute
was accessed through, or None
when the attribute is accessed through the owner class directly.
Return the attribute value or raise AttributeError
.
__set__(self, instance,
value)
Called to set the attribute on an instance of the owner class to a new value.
__delete__(self,
instance)
Called to delete the attribute on an instance of the owner class.
The following methods implement the context manager protocol, used by the
with
statement (see The with Statement).
__enter__(self)
Enter the runtime context related to this object. The
with
statement assigns this
method’s return value to the target specified in the as
clause of the statement (if
any).
__exit__(self, exc_type, exc_value,
traceback)
Exit the runtime context related to this object. The
parameters describe the exception that caused the context to be
exited. If the context exited without an exception, all three
arguments are None
. Return a
true value to prevent a raised exception from being propagated
by the caller.
The following methods are supported in Python 3.0 but not Python 2.X:
__bool__
(use method
name __nonzero__
in Python
2.X, or __len__
)
__next__
(use method
name next
in Python
2.X)
__truediv__
(available
in Python 2.X only if true division is enabled)
__dir__
__round__
__index__
for oct()
, hex()
(use __oct__
, __hex__
in Python 2.X)
The following methods are supported in Python 2.X but not Python 3.0:
__cmp__(self, other)
(and __rcmp__
)Invoked on self >
x
, x == self
,
cmp(self, x)
, etc. This
method is called for all comparisons for which no more
specific method (such as __lt__
) is defined or inherited. It
returns −1
, 0
, or 1
for self
less than, equal to, or greater
than other
. If no rich
comparison or __cmp__
methods are defined, class instances compare by their identity
(address in memory). The __rcmp__
right-side method is no
longer supported as of version 2.1.
In Python 3.0, use the more specific comparison methods
described earlier: __lt__
,
__ge__
, __eq__
, etc. Use __lt__
for sorting in Python
3.0.
__nonzero__(self)
Invoked on truth-value (otherwise, uses __len__
if defined).
In Python 3.0, this method is renamed __bool__
.
__getslice__(self, low,
high)
Invoked on self[low:high]
for sequence slicing.
If no __getslice__
is
found, and for extended three-item slices, a slice object is created and passed
to the __getitem__
method
instead.
In Python 2.X, this and the next two methods are
considered deprecated but are still supported—they are called
for slice expressions if defined, in preference to their
item-based counterparts. In Python 3.0, these three methods
are removed entirely—slices always invoke __getitem__
, __setitem__
, or __delitem__
instead, with a slice
object as its argument. See slice()
in Built-in Functions.
__setslice__(self, low, high,
seq)
Invoked on self[low:high]=seq
for sequence
slice assignment.
__delslice__(self, low,
high)
Invoked on del
self[low:high]
for sequence slice deletion.
__div__(self,
other)
(and __rdiv__
, __idiv__
)Invoked on self /
other
, unless true division is enable with from
(in which case __truediv__
is used). In Python 3.0,
these are always subsumed by __truediv__
, __rtruediv__
,
and __itruediv__
because
/
is always true
division.
__long__(self)
Invoked on long(self)
. In Python 3.0, the
int
type subsumes the
long
type
completely.
__oct__(self)
Invoked on oct(self)
.
This method returns an octal string representation. In Python
3.0, return an integer for __index__()
instead.
__hex__(self)
Invoked on hex(self)
.
This method returns a hex string representation. In Python
3.0, return an integer for __index__()
instead.
__coerce__(self,
other)
Invoked on the mixed-mode arithmetic expression,
coerce()
. This method
returns a tuple of (self,
other)
converted to a common type. If __coerce__
is defined, it is
generally called before any real operator methods are tried
(e.g., before __add__
). It
should return a tuple containing operands converted to a
common type (or None
if it
can’t convert). See the Python Language Reference (http://www.python.org/doc/) for more on
coercion rules.
__metaclass__
Class attribute assigned to class’s metaclass. In Python
3.0, use metaclass=M
keyword argument syntax in the class header line.