Is it possible to overload an operator for a builtin class in Python 3? Specifically, I'd like to overload the +/+= (i.e: __add__ operator for the str class, so that I can do things such as "This is a " + class(bla).
1 Answer
You can't change str's __add__, but you can define how to add your class to strings. I don't recommend it, though.
class MyClass(object):
...
def __add__(self, other):
if isinstance(other, str):
return str(self) + other
...
def __radd__(self, other):
if isinstance(other, str):
return other + str(self)
...
In "asdf" + thing, if "asdf".__add__ doesn't know how to handle the addition, Python tries thing.__radd__("asdf").
5 Comments
Joe
worked, thanks :). one question though - why don't you recommend it?
user2357112
@Joe: Pretty much nothing else auto-converts to a string when you add it to a string. The Python convention is to do string conversion explicitly.
kylieCatt
@Joe I think a better question is why do you think you need to do this?
Joe
@IanAuld really just to make it a bit simpler for the user
Stef
@Joe The more standard thing in python is to implement
__str__ or __repr__ for your class, so that the user can do "This is a " + str(bla)
str) or do you actually want to monkey patch? Why not usestr.format, rather than hacking your way to unreadable code?