Operator Overloading Methods

Classes intercept and implement built-in operations by providing specially named method functions, which all start and end with two underscores. These names are not reserved and may be inherited from superclasses as usual. At most one is located and called 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, then 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 may mix numeric and collection methods and mutable and nonmutable operations.

For All Types

_ _init_ _(self [, arg]*)

On class(args...). Constructor: initializes the new instance, self.

_ _del_ _(self)

On instance garbage collection. Cleans up when instance is freed. Embedded objects are automatically freed when parent is (unless referenced from elsewhere).

_ _repr_ _(self)

On `self`, repr(self), print self (if no _ _str_ _). Returns string representation.

_ _str_ _(self)

On str(self), print self (or uses _ _repr_ _ if defined). Returns string representation.

_ _cmp_ _(self, other), _ _rcmp_ _

On self > x, x == self, cmp(self, x), etc. Called for all comparisons for which no more specific method (such as _ _lt_ _) is defined or inherited (see rich comparison ...

Get Python Pocket Reference, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.