#!/usr/bin/env python#-*-coding:utf-8-*-import time as Tclass mytimer:def __init__ (self): #重写初始化函数 self.units =["Year", "Month", "Day", "hour", "Minute", "second", "self.lasted=[" #保存 the difference between the start and end times of the count is the time between minutes and seconds, and the time of day is reduced self.message= "not start timing!" def __str__ (self): #重新类的__str__函数 output string return self.message def __add__ (self, other): #重写类的__add__函数 called when the object calls the + sign Self.message = "A total of" result=["for item in range (6): #用循环 add total= in time position self.lasted[it Em]+other.lasted[item] If TOTAL:TS=STR (total) +self.units[item] Result.append (t s) self.message+=ts return self.message def __sub__ (self, Other): Self.message= "Two object time difference:" Result=[] for index in range (6): Lfs=self.lasted[index]-other.lasted[index] if LFS : Result.append (str (LFS) +self.units[index]) self.message+=str (LFS) +self.units[index] return Self.message def StArt (self): self.message= "counter already running:" Self.begintime = T.localtime () #取当前本地时间 def Stop (self): Self.en Dtime=t.localtime () #取当前结束时间 self.__sumtime () #开始计算时间差 def __sumtime (self): difference between #计算 start time and end time for item in rang E (6): Rs=self.endtime[item]-self.begintime[item] Self.lasted.append (RS) if (RS): Self.message+=str (RS) +self.units[item]t1=mytimer# create counter Object 1t1. Start () t.sleep (7) T1. Stop () print ("Object T1:" +str (T1)) T2=mytimer () #c创建计时器对象2t2. Start () t.sleep (1) T2. Stop () print ("Object t2:" +str (T2)) print (T1+T2) print (T1-T2)
Python Basic Learning 1-counter instance