鱼C论坛

 找回密码
 立即注册
查看: 863|回复: 2

请教关于算术运算的问题

[复制链接]
发表于 2018-12-28 23:43:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
>>> class New_int(int):
        def __add__(self,other):
                return int.__sub__(self,other)
        def __sub__(self,other):
                return int.__add__(self.other)

       
>>> a = New_int(3)
>>> b = int(5)
>>> a + b
-2
>>> a - b
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    a - b
  File "<pyshell#18>", line 5, in __sub__
    return int.__add__(self.other)
AttributeError: 'New_int' object has no attribute 'other'
>>> b - a
2
>>> b + a
8




请问这四种情况的区别???
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-12-28 23:59:18 | 显示全部楼层
self.
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-12-29 08:39:59 | 显示全部楼层
class New_int(int):
        def __add__(self,other):
                return int.__sub__(self,other)
        def __sub__(self,other):
                return int.__add__(self.other)

上面的“.”改成“,” 即可。

剩下的就是佳宇老师重写的add和sub,加法变成减法,减法变成加法了。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-12 17:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表