是否可以重载本机数据类型的运算符? [英] Is it possible to overload operators for native datatypes?

查看:55
本文介绍了是否可以重载本机数据类型的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我尝试这样做:

For example, if I try to do:

a_string + an_int

... 其中 a_string 是str"类型,an_int 是int"类型,或者:

... where a_string is type 'str' and an_int is type 'int', or:

an_int + a_string

会有一个 TypeError 因为没有类型的隐式转换.我知道如果我使用自己的 int 和 string 子类,我将能够在我的类中重载 __add__() 方法来实现这一点.

There would be a TypeError because there is no implicit conversion of the types. I understand that if I were using my own subclasses of int and string, I would be able to overload the __add__() method in my classes to achieve this.

但是,出于好奇,我想知道:是否可以在 intstr 的类定义中重载 + 运算符,以便 __add__(int,str)__add__(str,int) 自动将它们连接为字符串?

However, out of curiosity, I would like to know: would it be possible to overload the + operator in the class definitions of int and str, so that __add__(int,str) and __add__(str,int) automatically concatenate them as strings?

如果不是,程序员不应该重载本机数据类型的运算符的原因是什么?

If not, what are the reasons why a programmer should not overload the operators for a native datatype?

推荐答案

一般情况下,如果不恢复到 C 级 API,则无法修改内置类型的属性(参见 此处).但是,您可以对内置类型进行子类化并对新类型执行您想要的操作.对于您特别提出的问题(基于添加字符串),您需要修改 __add____radd__:

In general, without reverting to the C-level API, you cannot modify attributes of builtin types (see here). You can, however, subclass builtin types and do what you want on the new types. For the question you specifically asked (making the addition string based), you'd modify __add__ and __radd__:

class Int(int):
    def __add__(self, other):
        return Int(int(str(self) + str(other)))

    def __radd__(self, other):
        return Int(str(other) + str(self))

>>> Int(5) + 3
53

>>> 3 + Int(5) + 87
3587

这篇关于是否可以重载本机数据类型的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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