[ACCEPTED]-operator overloading in python-operator-overloading
As other answers have mentioned, you can 23 indeed overload operators (by definining 22 special methods in the class you're writing, i.e., methods 21 whose names start and end with two underscores). All 20 the details are here.
To complete the answers 19 to you questions: you cannot define new 18 operators; but
<< is not a new operator, it's 17 an existing one, and it's overloaded by 16 defining in the class the method
As a historical 15 note, this is also pretty much the situation 14 in C++ -- but the exact set of operators 13 you can overload differs between the two 12 languages. For example, in C++, you cannot 11 overload attribute access,
.; in Python, you 10 can, with
__getattribute__, with different semantics) and 9
__setattr__. Vice versa, in Python
= (plain assignment) is 8 not an operator, so you cannot overload 7 that, while in C++ it is an operator and 6 you can overload it.
<< is an operator, and 5 can be overloaded, in both languages -- that's 4 how
>>, while not losing their initial 3 connotation of left and right shifts, also 2 became I/O formatting operators in C++ (not 1 in Python!-).
A class can implement certain operations 7 that are invoked by special syntax (such 6 as arithmetic operations or subscripting 5 and slicing) by defining methods with special 4 names. This is Python’s approach to operator 3 overloading, allowing classes to define 2 their own behavior with respect to language 1 operators.
Yes, and no. I don't think you can define 5 your own operators, but you can overload 4 the existing ones - you can do that by overriding 3 the operator's special method. For example,
to 2 override >, you can override
__gt__(), for != override 1
__ne__() and so on.
More Related questions