|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def stop(self):
if not self.begin:
self.prompt = '请先用 start() 开始计时!'
里的 self.prompt = '请先用 start() 开始计时!'为什么在先stop的时候输出不了‘'请先用 start() 开始计时!’呢?而要改成 def stop(self):
if not self.begin:
print( '请先用 start() 开始计时!')
明明在 start 方法里就可以输出。。。
求各位大神指点,谢谢!!!- import time as t
- class MyTimer():
- def __init__(self):
- self.unit = ['年','月','日','时','分','秒']
- self.prompt = '未开始计时...'
- self.lasted = []
- self.begin = 0
- self.end = 0
- def __str__(self):
- return self.prompt
- __repr__ = __str__
- 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() #localtime返回元组(年月日时分秒)对应0-5
- #共6个索引值
- self.prompt = '请先用 stop() 停止计时!'
- print('计时开始...')
-
- #停止计时
- def stop(self):
- if not self.begin:
- self.prompt = '请先用 start() 开始计时!'
- else:
- self.end = t.localtime()
- self._calc()
- print('计时结束...')
-
- #内部方法,计算运行时间
- def _calc(self):
- self.lasted = []
- self.prompt = '总共运行了'
- for index in range(6): #对应前面localtime的元组索引值
- 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
复制代码
本帖最后由 Twilight6 于 2020-7-28 13:36 编辑
print 会自动调用 __str__ 或者 __repr__
而当两个魔法方法存在类中时,__str__ 主要负责 print 时候自动调用,而 __repr__ 主要负责对对象输出的时候自动调用
比如 t = MyTimer() 然后直接调用类对象,>>> t,此时自动调用 __repr__ ,打印__repr__ 设置的返回值,而__repr__ 被赋值为 __str__ 所以此时 t 相当于调用的是 __str__
而 __str__ 是当你 print(t) 此时自动调用
所以直接执行 t 的时候会自动打印的原因是因为自动调用了 __repr__ ,而你调用方法并不会自动调用 __repr__ 所以需要我们自己 print 打印
|
|