关于类中的方法名不能和属性名相同,因为会覆盖这一问题:
1)这里指的是初始化中的属性名不能跟类的方法名相同
2)方法名和方法中出现的属性(赋值)名,无所谓
因为你只能调用这个方法而不能越过方法直接调用方法中的属性对不?当然,最好还是别起一样的名字
import time as t
class Mytimer:
#prompt的初始化,对输出提示初始化之前用到的也是蛮少的
def __init__(self):
self.unit = ['年','月','天','时','分','秒']
self.prompt = '还未开始计时'
self.begin = 0
self.end = 0
self.lasted = []
#开始计时
def start(self):
self.begin = t.localtime()
self.prompt = '提示:请先调用stop()结束计时!' #采用这样的方式,是因为如果不调用stop而直接调用实例化对象,则返回该语句,而如果调用stop,则重写该属性值,PS:连续两次调用start,则重新开始计时
print('计时开始...')
#结束计时
def stop(self):
if not self.begin:
print('提示:请先调用start()开始计时!')
else:
self.end = t.localtime()
print('计时结束!')
self.calc()
#内部方法,计算运行时间
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.end = 0 print(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
'''这部分的作用是直接输入t1、t2的时候也能进行显示,它的显示不是print,而是直接显示的返回值 ,且等价于
def __str__(self):
return self.prompt
__repr__ = __str__
'''
def __repr__(self):
return self.prompt