O'Reilly logo

Python Pocket Reference, Second Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required