Can I overload operators for builtin classes in Python?

早过忘川 提交于 2019-12-31 05:31:28

问题


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



来源:https://stackoverflow.com/questions/37490116/can-i-overload-operators-for-builtin-classes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!