鱼C论坛

 找回密码
 立即注册
查看: 2756|回复: 8

Python 反运算问题?

[复制链接]
发表于 2017-2-9 15:51:10 | 显示全部楼层 |阅读模式
1鱼币
  1. >>> class Nint(int):
  2.         def __radd__(self, other):
  3.                 return int.__sub__(self, other)

  4.        
  5. >>> a = Nint(5)
  6. >>> b = Nint(8)
  7. >>> a + b
  8. 13
  9. >>> 5 + b
  10. 3
复制代码


为甚说5没法调用__add__方法呢,通过type:
  1. >>> type(a)
  2. <class '__main__.Nint'>
  3. >>> type(5)
  4. <class 'int'>
复制代码


5 属于‘int’类, 应该也有__add__方法啊

最佳答案

查看完整内容

a和b都是Nint类的实例化,a+b调用__add__,而class Nint没有写__add__,就直接调用int的__add__了。 5+b先调用int的__add__,但不支持Nint类型,转而调用Nint的__radd__了。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-9 15:51:11 | 显示全部楼层
a和b都是Nint类的实例化,a+b调用__add__,而class Nint没有写__add__,就直接调用int的__add__了。
5+b先调用int的__add__,但不支持Nint类型,转而调用Nint的__radd__了。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-2-9 21:42:12 | 显示全部楼层
冬雪雪冬 发表于 2017-2-9 20:55
a和b都是Nint类的实例化,a+b调用__add__,而class Nint没有写__add__,就直接调用int的__add__了。
5+b先 ...

哦哦 是因为int的__add__不支持Nint啊,明白了,谢谢~~
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-10 10:20:56 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-16 13:19:23 | 显示全部楼层
python我还没学到这个深入的地方
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-18 10:43:19 | 显示全部楼层
5是int 类,但不是Nint类
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-3-25 15:00:08 | 显示全部楼层
冬雪雪冬 发表于 2017-2-9 15:51
a和b都是Nint类的实例化,a+b调用__add__,而class Nint没有写__add__,就直接调用int的__add__了。
5+b先 ...

>>> class Nint(int):
        def __radd__(self, other):
                return int.__sub__(self, other)

        
>>> a = Nint(5)
>>> b = Nint(8)
>>> a + b
-3

请问为什么我电脑程序显示是-3 呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-3-25 20:46:30 | 显示全部楼层
luck78 发表于 2017-3-25 15:00
>>> class Nint(int):
        def __radd__(self, other):
                return int.__sub__(self, ...

不应该是这样的结果。
我试了一下:
  1. >>> class N(int):
  2.         def __radd__(self, other):
  3.                 return int.__sub__(self, other)

  4.        
  5. >>> a = N(5)
  6. >>> b = N(8)
  7. >>> a + b
  8. 13
复制代码


只有这样才会有你的结果
  1. >>> class N(int):
  2.         def __add__(self, other):
  3.                 return int.__sub__(self, other)

  4.        
  5. >>> a = N(5)
  6. >>> b = N(8)
  7. >>> a + b
  8. -3
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-3-26 16:44:26 | 显示全部楼层
冬雪雪冬 发表于 2017-3-25 20:46
不应该是这样的结果。
我试了一下:

。。。今天又试一次,结果如同你给的答案,奇怪为什么前两次试的时候都是-3,直接调用的是__sub__, 因为怕自己是不是写错了,我还直接复制代码去测试也是-3。然后今天就对了。。。。 谢谢你!

再请问一下上传代码,你们是怎么上传的?为什么有Notepad的格式? 我只会在shell里写好,复制黏贴过来。。。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-25 08:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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