Can I overload operators for builtin classes in Py

2019-03-03 13:15发布

问题:

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:

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