Operator Overloading Methods

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.

For All Types

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

Get Python Pocket Reference, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.