我可以重载 Python 中内置类的运算符吗?

Joe*_*Joe 6 overloading built-in python-3.x

是否可以为 Python 3 中的内置类重载运算符?具体来说,我想重载+/ +=(即:__add__类的运算符str,以便我可以执行诸如"This is a " + class(bla).

use*_*ica 5

您无法更改strs __add__,但您可以定义如何将类添加到字符串中。不过我不推荐它。

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)
        ...
Run Code Online (Sandbox Code Playgroud)

在 中"asdf" + thing,如果"asdf".__add__不知道如何处理加法,Python 会尝试thing.__radd__("asdf")