Tutorial by Examples

Magic (also called dunder as an abbreviation for double-underscore) methods in Python serve a similar purpose to operator overloading in other languages. They allow a class to define its behavior when it is used as an operand in unary or binary operator expressions. They also serve as implementation...
It is possible to emulate container types, which support accessing values by key or index. Consider this naive implementation of a sparse list, which stores only its non-zero elements to conserve memory. class sparselist(object): def __init__(self, size): self.size = size se...
class adder(object): def __init__(self, first): self.first = first # a(...) def __call__(self, second): return self.first + second add2 = adder(2) add2(1) # 3 add2(2) # 4
If your class doesn't implement a specific overloaded operator for the argument types provided, it should return NotImplemented (note that this is a special constant, not the same as NotImplementedError). This will allow Python to fall back to trying other methods to make the operation work: When...
Below are the operators that can be overloaded in classes, along with the method definitions that are required, and an example of the operator in use within an expression. N.B. The use of other as a variable name is not mandatory, but is considered the norm. OperatorMethodExpression+ Addition__add...

Page 1 of 1