|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
参考课程讲解的内容,利用time.time的方式进行课程作业完成,但遇到两个问题
1、__repr__ = __str__不生效
使用此语法后,直接输入对象名称并不会进行打印
2、__add__不生效
重写add方法后,仍然提示错误
代码及报错如下
- class Myime:
- def __init__(self):
- self.start_time = 0
- self.end_time = 0
- self.result = 0
- def __str__(self):
- if not self.start_time and not self.end_time:
- return '未开始计时!'
- elif not self.end_time:
- return '提示:请先调用stop()开始计时!'
- elif self.start_time and self.end_time:
- self.result = self.end_time - self.start_time
- return f'总共运行了{self.result}秒'
- def start(self):
- self.start_time = time.time()
- print("计时开始……")
- def stop(self):
- if not self.start_time:
- print('提示:请先调用start()开始计时!')
- else:
- self.end_time = time.time()
- print("计时结束!")
- # 利用赋值的方式使得直接打印
- __repr__ = __str__
- def __add__(self, other):
- temp = self.result + other.result
- return f'总共运行了{temp}秒'
-
- t1 = Mytime()
- t1
- <__main__.Mytime object at 0x000001765AF3E020>
- print(t1)
- 未开始计时!
- t1.start()
- 计时开始……
- print(t1)
- 提示:请先调用stop()开始计时!
- t1
- <__main__.Mytime object at 0x000001765AF3E020>
- t1.stop()
- 计时结束!
- print(t1)
- 总共运行了15.581618547439575秒
- t2 = Mytime()
- t2.start()
- 计时开始……
- print(t2)
- 提示:请先调用stop()开始计时!
- t2.stop()
- 计时结束!
- t1+t2
- Traceback (most recent call last):
- File "<pyshell#30>", line 1, in <module>
- t1+t2
- TypeError: unsupported operand type(s) for +: 'Mytime' and 'Mytime'
- print(t1+t2)
- Traceback (most recent call last):
- File "<pyshell#31>", line 1, in <module>
- print(t1+t2)
- TypeError: unsupported operand type(s) for +: 'Mytime' and 'Mytime'
复制代码
|
|