一:魔法方法
1.__str__()
>>> class A(): def __str__(self): return "小甲鱼是帅哥" >>> a=A() >>> print(a) 小甲鱼是帅哥
2.__repr__()
>>> class B(): def __repr__(self): return "小甲鱼是帅哥" >>> b=B() >>> b 小甲鱼是帅哥
3.简单定制:
基本要求:
定制一个计时器类
start和stop方法代表启动计时和停止计时
假设计时器对象t1,print(t1)和直接调用t1均显示结果
当计时器未启动或已经停止计时,调用stop方法会给予温馨提示
两个计时器对象可以进行相加:t1+t2
只能使用提供有限资源完成
import time as t class MyTime(): def __init__(self): #进行变量和函数的初始化 self.unit=['年','月','天','时','分','秒'] #时间单位 self.prompt='未开始计时' #提示语句 self.lasted=[] #持续时间存储的列表 self.begin=0 #开始时间初始化 self.end=0 #结束时间初始化 def __str__(self): #调用实例直接显示结果 return self.prompt def __repr__(self): return self.prompt def __add__(self, other): prompt='总共运行了' result=[] for index in range(6): result.append(self.lasted[index]+other.lasted[index]) if result[index]: prompt+=(str(result[index])+self.unit[index]) return prompt #开始计时 def start(self): self.begin=t.localtime() self.prompt='提示:请先调用stop停止计时' print('计时开始..') #内部方法,计算运行时间 def _calc(self): self.lasted=[] self.prompt='总共运行了' for index in range(6):#只要前六位返回的结果 self.lasted.append(self.end[index]-self.begin[index]) if self.lasted[index]: self.prompt+=(str(self.lasted[index])+self.unit[index]) self.begin=0 self.end=0 print(self.prompt) #停止计时 def stop(self): if not self.begin: print('提示:请先调用start()进行计时') else: self.end=t.localtime() self._calc() print('计时结束!') t1=MyTime() t2=MyTime() t1.start() t.sleep(45) t1.stop() t2.start() t.sleep(15) t2.stop() print(t1+t2)
使用time模块的localtime方法获取时间。time.localtime返回struct_time的时间格式:
包括:tm_year 年
月 tm_mon
日 tm_mday
时 tm_hour
分 tm_min
秒tm_sec
weekday:0-6 0表示周日 tm_wday
一年中的第几天1-366 tm_yday
是否是夏令时 tm_isdst