6

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
  • Do you actually mean overload (i.e. you're subclassing str) or do you actually want to monkey patch? Why not use str.format, rather than hacking your way to unreadable code? Commented May 27, 2016 at 18:33

1 Answer 1

6

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").

Sign up to request clarification or add additional context in comments.

5 Comments

worked, thanks :). one question though - why don't you recommend it?
@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.
@Joe I think a better question is why do you think you need to do this?
@IanAuld really just to make it a bit simpler for the user
@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.