|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class MyTimer(int):
def __add__(self,other):
obj_time_total = int.__add__((self.end - self.start),(other.end - other.start))
return '总共用时' + str(obj_time_total)
def __init__(self):
self.begin = 0
self.end = 0
self.feedback = '未开始计时'
def __str__(self):
return self.feedback
def __repr__(self):
return self.feedback
def start(self):
self.feedback = '请先停止计时'
#开始时间
self.begin = t.perf_counter()
def stop(self):
if not self.begin:
print('请先开始计时')
else:
self.end = t.perf_counter()
print('计时停止')
self.count_time()
def count_time(self):
self.feedback = '总计时:'
total = self.end - self.begin
print('%s%f秒' % (self.feedback,total))
t1 = MyTimer()
t1.start()
t.sleep(2)
t1.stop()
t2 = MyTimer()
t2.start()
t.sleep(1)
t2.stop()
t1 + t2
print(t1)
print(t2)
为什么会报错
Traceback (most recent call last):
File "D:/python代码库/My_timer.py", line 58, in <module>
t1 + t2
File "D:/python代码库/My_timer.py", line 17, in __add__
obj_time_total = int.__add__((self.end - self.start),(other.end - other.start))
TypeError: unsupported operand type(s) for -: 'float' and 'method'
1、你定义的类是继承于int类。
class MyTimer(int):
2、出错代码在t1 + t2,t1和t2都是继承于int的MyTimer类的实例化对象
t1+t2的时候,会自动调用int.__add__方法,但这个方法只支持整数形,因此会报错
|
|