Possible Duplicates:
Python: defining my own operators?
Rules of thumb for when to use operator overloading in python
Is it possible to overload operators in Python? If so, can one define new operators, such as ++
and <<
?
Possible Duplicates:
Python: defining my own operators?
Rules of thumb for when to use operator overloading in python
Is it possible to overload operators in Python? If so, can one define new operators, such as ++
and <<
?
See: http://docs.python.org/reference/datamodel.html#special-method-names.
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.
Yes, and no. I don't think you can define your own operators, but you can overload the existing ones - you can do that by overriding the operator's special method. For example,
to override >, you can override __gt__()
, for != override __ne__()
and so on.