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 <<?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As other answers have mentioned, you can indeed overload operators (by definining special methods in the class you’re writing, i.e., methods whose names start and end with two underscores). All the details are here.
To complete the answers to you questions: you cannot define new operators; but
<<is not a new operator, it’s an existing one, and it’s overloaded by defining in the class the method__lshift__.As a historical note, this is also pretty much the situation in C++ — but the exact set of operators you can overload differs between the two languages. For example, in C++, you cannot overload attribute access,
.; in Python, you can, with__getattr__(or__getattribute__, with different semantics) and__setattr__. Vice versa, in Python=(plain assignment) is not an operator, so you cannot overload that, while in C++ it is an operator and you can overload it.<<is an operator, and can be overloaded, in both languages — that’s how<<and>>, while not losing their initial connotation of left and right shifts, also became I/O formatting operators in C++ (not in Python!-).