python中加法运算符的重载,python中的运算符重载

Is it possible to overload operators in Python? If so, can one define new operators, such as ++ and <

解决方案

As other answers have mentioned, you can indeed overload operators (by definining special methods in the class you're writing, i.e., methods whose names start and end with two underscores). All the details are here.

To complete the answers to you questions: you cannot define new operators; but << is not a new operator, it's an existing one, and it's overloaded by defining in the class the method __lshift__.

As a historical note, this is also pretty much the situation in C++ -- but the exact set of operators you can overload differs between the two languages. For example, in C++, you cannot overload attribute access, .; in Python, you can, with __getattr__ (or __getattribute__, with different semantics) and __setattr__. Vice versa, in Python = (plain assignment) is not an operator, so you cannot overload that, while in C++ it is an operator and you can overload it.

<< is an operator, and can be overloaded, in both languages -- that's how << and >>, while not losing their initial connotation of left and right shifts, also became I/O formatting operators in C++ (not in Python!-).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值