Python3.3.2 算术运算----方法重写

来源:互联网 发布:淘宝卖家破损补寄 编辑:程序博客网 时间:2024/06/06 02:30

当对象进行相关的算术运算的时候,会自然的调用相应的方法。一旦你复写了这些方法,Python就会根据你的意图去进行计算。这和Java中的继承,子类复写父类方法,以及this和super的用法相似。我们可以通过对指定方法的重写,完全可以让Python根据我们的意图去实现程序。下面看一些例子:

>>> class Myint(int):
def __add__(self,other):
print(type(self),'\n',type(other),type(int(self)))
return int(self)+int(other)



>>> a=Myint(1)
>>> b=Myint(3)
>>> a+b
<class '__main__.Myint'> 
 <class '__main__.Myint'> <class 'int'>
4
>>> 

0 0
原创粉丝点击