|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 是微微呀 于 2019-7-28 22:49 编辑
#计时器
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 start(self):
self.begin = t.localtime #获取计时开始时当地时间
self.prompt = '请先调用stop停止计时!'
print('计时开始:')
def stop(self):
if not self.begin:
print('请先调用start开始计时!')
else:
self.end = t.localtime #获取计时结束时当地时间
self.__calc()
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]) + str(self.unit[index])
self.begin = 0 #为下一轮初始化做准备
self.end = 0
a = Mytimer()
a.start()
a.stop()
a
问题如下:
1.def __init__(self) 是用来避免内部参数被修改的吗?这个模块里self.unit等参数在后面也被修改了呀?
2.self.unit,self.prompt是怎么理解的?也是像例如t.localtime一样调用time模块的localtime函数?这样理解好像有点怪啊。。
3.运行该程序报错:
错误如下:
File "<ipython-input-37-cc8a1570ed9f>", line 33
self.prompt += str(self.lasted[index]) + str(self.unit[index])
^
IndentationError: expected an indented block
跪求各路大佬帮忙!好人一生平安
1. 不是。__init__ 魔法方法只是一个初始化方法,它返回类的实例
2. self.unit 是表示时间单位,self.prompt 表示用户打印计时器时给出的提示
|
|