调用未绑定的父类方法和使用supper 函数 之间的选择.
2016-07-16 21:58
393 查看
class New_int(int): # 定义一个新的类 继承 int 类 def __add__(self,other): # 重写 + 运算符 # __add__ 就是 int 中 + 的行为 return int.__sub__(self,other) # 重写的 加法运算符 调用 int类 里面的 减法运算运算符 def __sub__(self,other): return int.__add__(self,other) # 上面的是一个小小的恶作剧 . 把加法和减法的名称进行了互换.
>>> a=New_int(5) >>> b=New_int(3) >>> a+b 2
上面的是调用未绑定的父类方法.
下面是使用super函数
class New_int(int): # 定义一个新的类 继承 int 类 def __add__(self,other): # 重写 + 运算符 # __add__ 就是 int 中 + 的行为 return super.__sub__(self,other) # 重写的 加法运算符 调用 int类 里面的 减法运算运算符 def __sub__(self,other): return super.__add__(self,other) # 上面的是一个小小的恶作剧 . 把加法和减法的名称进行了互换.
=============== RESTART: C:/Users/Administrator/Desktop/new.py =============== >>> a=New_int(5) >>> b=New_int(3) >>> a+b Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> a+b File "C:/Users/Administrator/Desktop/new.py", line 3, in __add__ return super.__sub__(self,other) # 重写的 加法运算符 调用 int类 里面的 减法运算运算符 AttributeError: type object 'super' has no attribute '__sub__'
可见当使用super的时候 报错提示 super中没有__sub__ .......然而我不知道为什么会这样 . 网上没找到相关资料 . 等学的多了 ,再来看看 .
class int(int): def __add__(self,other): return int.__sub__(self,other) '''def __sub__(self,other): return int.__add__(self,other)''' # 上面的 两个重写只能在同一时间内重写一个 , 不然的话 , 就会报错..... # 当写第二个的 add 的时候 系统不知道 会认为是 你重写的 add 然后程序就崩溃了.
相关文章推荐
- angular2.0 webpack css url 图片路径问题
- POJ 3070 Fibonacci
- 判断是否是完全二叉树
- 近似因子模型
- 快速排序(完整程序c语言实现)
- solr Hello, World!
- 图形引擎(二):初始化Direct3D
- c和指针1~2章小结
- ng Expresss POST
- rsync 不能复制数据
- ChatForFun 公众号使用说明
- 奶牛排队 (Standard IO)
- 深入理解Java的接口和抽象类
- 【Get深一度】超炫的机器人公司Boston Dynamics(波士顿动力)
- 【Linux系统】Ubuntu之虚拟机 ping 通宿主机,宿主机 ping 不通虚拟机
- a 标签属性在点击后出现一层阴影
- java网络编程(上)
- JS 获取浏览器窗口大小
- SolrJ是操作Solr的JAVA客户端
- scikit-learn 回归基础