我可以在Python中为内置类重载运算符吗? [英] Can I overload operators for builtin classes in Python?

查看:86
本文介绍了我可以在Python中为内置类重载运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您不能更改str__add__,但是您可以定义如何将您的类添加到字符串中.不过,我不建议这样做.

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

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

In "asdf" + thing, if "asdf".__add__ doesn't know how to handle the addition, Python tries thing.__radd__("asdf").

这篇关于我可以在Python中为内置类重载运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆