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