鱼C论坛

 找回密码
 立即注册
查看: 2625|回复: 3

[已解决]关于class类的一个问题。。

[复制链接]
发表于 2016-8-11 13:16:41 | 显示全部楼层 |阅读模式

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

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

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

这里的    class New_int(int):   是指New_int 是  int的一个子类  还是可以传入一个int类的实例化对象呢?
下面是我写的一个,运行出错, 为啥不能这样写呢?
class New_int:
        def __init__(self,a):
                self.a=a
        def __add__(self,other):
                return a.__sub__(self,other)

a=New_int(5)
b=New_int(3)
a+b
Traceback (most recent call last):
  File "<pyshell#119>", line 1, in <module>
    a+b
  File "<pyshell#116>", line 5, in __add__
    return a.__sub__(self,other)
AttributeError: 'New_int' object has no attribute '__sub__'
最佳答案
2016-8-11 17:00:11
__sub__() 方法是继承于 int 类的

不懂欢迎追问
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-8-11 17:00:11 | 显示全部楼层    本楼为最佳答案   
__sub__() 方法是继承于 int 类的

不懂欢迎追问
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-8-11 17:15:30 | 显示全部楼层
        def __add__(self,other):
                return a.__sub__(self,other)

a=New_int(5)

a 碰巧和全局变量同名,
self 不能放这里
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-8-12 08:22:22 | 显示全部楼层
SixPy 发表于 2016-8-11 17:15
def __add__(self,other):
                return a.__sub__(self,other)

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(5)  5 这个值   就是传给self了吧  但是没有__init__是怎么传进去的呢。。
一般不都是a=New_int  
               a.xxx(5)   这样的方式传入5这个值么  
  或者在函数里有__init__的时候 可以 a=New_int(5)  把这个值通过__init__这个方法传入的

因为__add__  __sub__也是魔法方法   是不是 只要是魔法方法都可以通过a=New_int(5) 直接传入一个值呢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-25 16:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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