python学习之运用特殊方法,定制类

Posted 秋雨的蝴蝶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之运用特殊方法,定制类相关的知识,希望对你有一定的参考价值。

class Time60(object):
def __init__(self,hr,min):
self.hr=hr
self.min=min

def __add__(self, other): #__add__ 相当于加:+操作符
return self.__class__(self.hr+other.hr,self.min+other.min)
#self.__class__()等价Time60()

def __str__(self):
return ‘%d:%d‘%(self.hr,self.min)
__repr__=__str__

def __iadd__(self, other): #__iadd__相当于:+=操作符
self.hr+=other.hr
self.min+=other.min
return self

test1=Time60(1,30)
test2=Time60(12,45)
print(test1,test2)
print(test1+test2)
test1+=test2
print(test1)

以上是关于python学习之运用特殊方法,定制类的主要内容,如果未能解决你的问题,请参考以下文章

Python学习之绑定方法与非绑定方法

Python模块学习之特殊函数 __call__ 的使用

Python学习之标识符

Python 定制类 特殊方法

Python学习之抽象类详解

python3学习之特殊变量