Next / Previous / Contents / Shipman's homepage

26.3. Special method names

Within a class, a number of reserved method names have special meaning. Here is a list of the ones covered in this document.

__abs__ Section 26.3.4, “Special methods to emulate built-in functions”
__add__ Section 26.3.2, “Special methods for binary operators”
__and__ Section 26.3.2, “Special methods for binary operators”
__call__ Section 26.3.5, “__call__(): What to do when someone calls an instance”
__cmp__ Section 26.3.6, “__cmp__(): Generalized comparison”
__complex__ Section 26.3.4, “Special methods to emulate built-in functions”
__contains__ Section 26.3.7, “__contains__(): The “in” and “not in” operators”
__del__ Section 26.3.8, “__del__(): Destructor”
__delattr__ Section 26.3.9, “__delattr__(): Delete an attribute”
__delitem__ Section 26.3.10, “__delitem__(): Delete one item of a sequence”
__divmod__ Section 26.3.4, “Special methods to emulate built-in functions”
__div__ Section 26.3.2, “Special methods for binary operators”
__divmod__ Section 26.3.4, “Special methods to emulate built-in functions”
__enter__ Section 26.3.11, “__enter__: Context manager initialization”
__exit__ Section 26.3.12, “__exit__: Context manager cleanup”
__eq__ Section 26.3.1, “Rich comparison methods”
__floordiv__ Section 26.3.2, “Special methods for binary operators”
__float__ Section 26.3.4, “Special methods to emulate built-in functions”
__ge__ Section 26.3.1, “Rich comparison methods”
__getattr__ Section 26.3.14, “__getattr__(): Handle a reference to an unknown attribute”
__getattribute__ Section 26.3.15, “__getattribute__(): Intercept all attribute references”
__getitem__ Section 26.3.16, “__getitem__(): Get one item from a sequence or mapping”
__gt__ Section 26.3.1, “Rich comparison methods”
__hex__ Section 26.3.4, “Special methods to emulate built-in functions”
__iadd__ Section 26.3.2, “Special methods for binary operators”
__iand__ Section 26.3.2, “Special methods for binary operators”
__idiv__ Section 26.3.2, “Special methods for binary operators”
__ifloordiv__ Section 26.3.2, “Special methods for binary operators”
__ilshift__ Section 26.3.2, “Special methods for binary operators”
__imod__ Section 26.3.2, “Special methods for binary operators”
__imul__ Section 26.3.2, “Special methods for binary operators”
__init__ Section 26, “Classes: Defining your own types”
__int__ Section 26.3.4, “Special methods to emulate built-in functions”
__invert__ Section 26.3.3, “Unary operator special methods”
__ior__ Section 26.3.2, “Special methods for binary operators”
__ipow__ Section 26.3.2, “Special methods for binary operators”
__irshift__ Section 26.3.2, “Special methods for binary operators”
__isub__ Section 26.3.2, “Special methods for binary operators”
__iter__ Section 26.3.17, “__iter__(): Create an iterator”
__ixor__ Section 26.3.2, “Special methods for binary operators”
__le__ Section 26.3.1, “Rich comparison methods”
__len__ Section 26.3.4, “Special methods to emulate built-in functions”
__long__ Section 26.3.4, “Special methods to emulate built-in functions”
__lshift__ Section 26.3.2, “Special methods for binary operators”
__lt__ Section 26.3.1, “Rich comparison methods”
__mod__ Section 26.3.2, “Special methods for binary operators”
__mul__ Section 26.3.2, “Special methods for binary operators”
__ne__ Section 26.3.1, “Rich comparison methods”
__neg__ Section 26.3.3, “Unary operator special methods”
__new__ Section 26.2.1, “__new__(): New instance creation”
__nonzero__ Section 26.3.18, “__nonzero__(): True/false evaluation”
__oct__ Section 26.3.4, “Special methods to emulate built-in functions”
__or__ Section 26.3.2, “Special methods for binary operators”
__pos__ Section 26.3.3, “Unary operator special methods”
__pow__ Section 26.3.2, “Special methods for binary operators”
__radd__ Section 26.3.2, “Special methods for binary operators”
__rand__ Section 26.3.2, “Special methods for binary operators”
__rdiv__ Section 26.3.2, “Special methods for binary operators”
__repr__ Section 26.3.19, “__repr__(): String representation”
__reversed__ Section 26.3.20, “__reversed__(): Implement the reversed() function”
__rfloordiv__ Section 26.3.2, “Special methods for binary operators”
__rlshift__ Section 26.3.2, “Special methods for binary operators”
__rmod__ Section 26.3.2, “Special methods for binary operators”
__rmul__ Section 26.3.2, “Special methods for binary operators”
__ror__ Section 26.3.2, “Special methods for binary operators”
__rpow__ Section 26.3.2, “Special methods for binary operators”
__rrshift__ Section 26.3.2, “Special methods for binary operators”
__rshift__ Section 26.3.2, “Special methods for binary operators”
__rsub__ Section 26.3.2, “Special methods for binary operators”
__rxor__ Section 26.3.2, “Special methods for binary operators”
__setattr__ Section 26.3.21, “__setattr__(): Intercept all attribute changes”
__setitem__ Section 26.3.22, “__setitem__(): Assign a value to one item of a sequence”
__str__ Section 26.3.4, “Special methods to emulate built-in functions”
__sub__ Section 26.3.2, “Special methods for binary operators”
__unicode__ Section 26.3.4, “Special methods to emulate built-in functions”
__xor__ Section 26.3.2, “Special methods for binary operators”

The most important special method name is the class constructor, .__init__().

Many special methods fall into broad categories:

26.3.1. Rich comparison methods

These special methods allow your class to specify what happens when comparison operators such as “<=” are used, and the left-hand operator is an instance of your class. (In most cases the right-hand operator is also an instance of the same class, but this is not actually required.)

In each case, the calling sequence for the method must look like this:

    def __method__(self, other):
        ...

The self argument is the left-hand operand and the other argument is the operand on the right hand of the operator.

Each method must return a numeric value:

  • A negative number indicates that self precedes other.

  • Zero indicates that self and other are considered equal.

  • A positive number indicates that other precedes self.

  • If the method does not implement the operation, it may return the special value NotImplemented.

OperatorMethod name
==__eq__
>=__ge__
>__gt__
<=__le__
<__lt__
!=__ne__

26.3.2. Special methods for binary operators

Your class can define special methods with these names to tell Python how to handle binary operators such as “*” or “%”. In each case, the calling sequence will look something like this:

    def __method__(self, other):
        ...

The self argument is the left-hand operand, and the other argument is the right-hand operand. Your method will return the result of the operation.

For each operator, you may supply up to three methods:

  • The method in the first column performs the normal operation.

  • The method in the second column is used when the left-hand operand does not support the given operation and the operands have different types. In these methods, self is the right-hand operand and other is the left-hand operand.

  • The third column implements the “augmented assignment” operators such as “+=”. For example, for method __iadd__(self, other), the method must perform the equivalent of “self += other”.

OperatorNormalReversedAugmented
+__add____radd____iadd__
&__and____rand____iand__
/__div____rdiv____idiv__
//__floordiv____rfloordiv____ifloordiv__
<<__lshift____rlshift____ilshift__
%__mod____rmod____imod__
*__mul____rmul____imul__
|__or____ror____ior__
**__pow____rpow____ipow__
>>__rshift____rrshift____irshift__
-__sub____rsub____isub__
^__xor____rxor____ixor__

26.3.3. Unary operator special methods

You can define these special methods in your class to specify what happens when a unary operator such as “-” (negate) is applied to an instance of the class.

In each case, the definition will look like this:

    def __method__(self):
        ...

The method returns the result of the operation.

OperatorMethod
~__invert__
-__neg__
+__pos__

26.3.4. Special methods to emulate built-in functions

You can define special methods that will handle calls to some of Python's built-in functions. The number of arguments will be the same as for the built-in functions, except that self is always the first argument.

For example, a special method to handle calls to function divmod(x, y) will look like this:

    def __divmod__(self, other):
        ...

In this method, the value of the first argument will be passed to self and the second argument to other.

FunctionMethod
abs__abs__
complex__complex__
divmod__divmod__
hex__hex__
int__int__
len__len__
long__long__
mod__mod__
oct__oct__
str__str__
unicode__unicode__

26.3.5. __call__(): What to do when someone calls an instance

If a class has a .__call__() method, its instances can be called as if they were functions.

Any arguments passed in that function call become arguments to the .__call__() method. Example:

>>> class CallMe(object):
...     def __call__(self, *p, **k):
...         print "CallMe instance called with:"
...         print "Positional arguments", p
...         print "Keyword arguments", k
... 
>>> c=CallMe()
>>> c(1, 'rabbit', fetchez='la vache', hamster='elderberries')
CallMe instance called with:
Positional arguments (1, 'rabbit')
Keyword arguments {'fetchez': 'la vache', 'hamster': 'elderberries'}

26.3.6. __cmp__(): Generalized comparison

The purpose of this special method is to implement comparison operations between instances. It will be called in these situations:

  • If the built-in cmp() function is called to compare an instance of a class to some other value, and the class has a .__cmp__() method, that method is called to perform the comparison.

  • When an instance appears on the left-hand side of a comparison (relational) operator, and that instance's class has a the corresponding rich-comparison method (such as .__eq__() for the “==” operator; see Section 26.3.1, “Rich comparison methods”), the rich-comparison method will be called to perform the comparison. and, if so, that method is called.

    The comparison operators are “<”, “<=”, “==”, “!=”, “>”, and “>=”.

    However, if the class does not have the correct rich-comparison method, but it does have a .__cmp__() method, that method will be called to evaluate the comparison.

The calling sequence is:

    def __cmp__(self, other):
        ...

The convention for return values is the same one described in Section 20.8, “cmp(): Compare two values”: negative if self precedes other, positive if other precedes self, zero if they are considered equal.

26.3.7. __contains__(): The “in” and “not in” operators

This special method defines how instances of a class behave when they appear as the right-hand operand of Python's “in” and “not in” operators.

Here is the calling sequence:

    def __contains__(self, x):
        ...

The method returns True if x is considered to be in self, False otherwise.

26.3.8. __del__(): Destructor

If a class has a .__del__() method, that method is called when an instance is deleted. For details, see Section 26.1.5, “Instance deletion: the destructor, .__del__().

26.3.9. __delattr__(): Delete an attribute

If a class has a .__delattr__() method, that method is called when an attribute is deleted. Here is the calling sequence:

    def __delattr__(self, name):
        ...

The name argument is the name of the attribute to be deleted.

26.3.10. __delitem__(): Delete one item of a sequence

This method defines the behavior of a del statement of this form:

del s[i]

Such a statement can be used either on objects that act like sequences, where i specifies the position of the element to be deleted, or mapping objects (that is, dictionary-like objects), where i is the key of the key-value pair to be deleted.

The calling sequence is:

    def __delitem__(self, i):
        ...

26.3.11. __enter__: Context manager initialization

For a general explanation of context managers, see Section 23.9, “The with statement and context managers”. A class that acts a content manager must provide this special method as well as the one described in Section 26.3.12, “__exit__: Context manager cleanup”.

The expression that follows the word with in the with statement must evaluate to a context manager, whose .__enter__() method is called with no arguments (other than self). The value it returns will be bound to the variable named in the with statement's as clause, if one was provided.

26.3.12. __exit__: Context manager cleanup

For a general explanation of context managers, see Section 23.9, “The with statement and context managers”. A class that acts a content manager must provide this special method as well as the one described in Section 26.3.11, “__enter__: Context manager initialization”.

When the body of a with statement completes its execution, the .__exit__() method of the related context manager M is called with three arguments. If the block terminated without raising an exception, all three arguments will be None; otherwise see below.

M.__exit__(self, eType, eValue, eTrace)
eType

The type of the exception.

eValue

The exception instance raised.

eTrace

A traceback instance. For more information about stack traces, see the documentation for the traceback module.

Your .__exit__() method's return value determines what happens next if the block raised an exception. If it returns True, Python ignores the exception and proceeds with execution at a point just after the with block. If you don't want your context manager to suppress the exception, don't re-raise it explicitly, just return False and Python will then re-raise the exception.

26.3.13. __format__: Implement the format() function

Use this special method to determine how an instance of your class acts when passed to the function described in Section 20.16, “format(): Format a value”. The calling sequence is:

    def __format__(self, fmt):
        ...

The interpretation of the fmt argument is entirely up to you. The return value should be a string representation of the instance.

If the call to the format() function does not provide a second argument, the fmt value passed to this method will be an empty string.

26.3.14. __getattr__(): Handle a reference to an unknown attribute

This method, if present, handles statements that get an attribute value of an instance, but there is no such entry in the instance's namespace. The calling sequence is:

    def __getattr__(self, name):
        ...

The argument is the name of the desired attribute. The method must either return the attribute's value or raise an AttributeError exception.

Compare Section 26.3.15, “__getattribute__(): Intercept all attribute references”, which is called even if the instance namespace does have an attribute with the desired name.

26.3.15. __getattribute__(): Intercept all attribute references

This method is called whenever an attribute is referenced, whether the instance or class namespace has an attribute with the given name or not. It works only with new-style classes.

For an overview and examples, see Section 26.2.2, “Attribute access control in new-style classes”.

26.3.16. __getitem__(): Get one item from a sequence or mapping

If a class defines it, this special method is called whenever a value is retrieved from a sequence or mapping (dictionary-like object) using the syntax “v[i]”, where v is the sequence or mapping and i is a position in a sequence, or a key in a mapping.

Here is the calling sequence:

    def __getitem__(self, i):
        ...

The method either returns the corresponding item or raises an appropriate exception: IndexError for sequences or KeyError for mappings.

26.3.17. __iter__(): Create an iterator

If a class defines an .__iter__() method, that method is called:

  • Whenever the built-in iter() function is applied to an instance of the class.

  • In any situation where the instance is iterated over, such as when it appears as the controlling iterable of a for statement.

The calling sequence is:

    def __iter__(self):
        ...

The return value must be an iterator. An iterator is any object that has a .next() method that returns the next value in the sequence, or raises StopIteration when the sequence is exhausted. For more information, see Section 24.2, “Iterators: Values that can produce a sequence of values”.

26.3.18. __nonzero__(): True/false evaluation

If a class defines it, this special method is called whenever an instance is converted to a Boolean value, either implicitly (for example, when it is the test in an “if” statement) or explicitly via the built-in bool() function. Here is the calling sequence:

    def __nonzero__(self):
        ...

Return a Boolean value, either True or False.

26.3.19. __repr__(): String representation

If a class defines it, this special method is called to find the “representation” of an object. There are two ways to get a representation:

The calling sequence is:

    def __repr__(self):
        ...

The method returns the representation of self as a string.

26.3.20. __reversed__(): Implement the reversed() function

If provided, this method allows the reversed() function to be applied to an instance of the class. It returns an iterator that iterates over the contained elements in reverse order.

26.3.21. __setattr__(): Intercept all attribute changes

If a class defines it, this method is called whenever a new value is stored into an attribute. Calling sequence:

    def __setattr__(self, name, value):
        ...

The method sets the attribute given by the name argument to the value argument, or raises AttributeError if that operation is not permitted.

26.3.22. __setitem__(): Assign a value to one item of a sequence

If a class defines it, this method is called whenever a new value is stored into a sequence or mapping (dictionary-like object), such as in statements of this form:

V[i]  =  expr

Here is the calling sequence:

    def __setitem__(self, i, value):
        ...

For sequence-type objects, the i argument specifies the position in the sequence to be modified. For mappings, the i argument is the key under which the value is to be stored.