有点迷
import time as tclass MyTimer():
# 开始计时
def start(self):
self.start = t.localtime()
print('计时器开始计时')
#计时器停止计时
def stop(self):
self.stop = t.localtime()
self.__calc()
print('计时器结束计时')
#内部方法,计算运行时间
def __calc(self):
self.lasted = []
self.prompt = '总共运行了'
for index in range(6):
self.lasted.append(self.stop - self.start)
self.prompt += str(self.lasted)
print(self.prompt)
报错
self.__calc()
AttributeError: 'MyTimer' object has no attribute '_MyTimer__calc'
zltzlt 发表于 2020-8-17 15:23
__calc 不用加双下划线
哦哦
你的 __calc 方法缩进错了,少打一个缩进就好
参考代码:
import time as t
class MyTimer():
# 开始计时
def start(self):
self.start = t.localtime()
print('计时器开始计时')
#计时器停止计时
def stop(self):
self.stop = t.localtime()
self.__calc()
print('计时器结束计时')
#内部方法,计算运行时间
def __calc(self):
self.lasted = []
self.prompt = '总共运行了'
for index in range(6):
self.lasted.append(self.stop - self.start)
self.prompt += str(self.lasted)
print(self.prompt) zltzlt 发表于 2020-8-17 15:23
__calc 不用加双下划线
去掉和加上都会报错Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
t1.stop()
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/这节课听的我是迷迷瞪瞪的.py", line 12, in stop
self.calc()
AttributeError: 'MyTimer' object has no attribute 'calc' 你的__calc函数的缩进搞错了
你把__calc函数写成了stop函数内的一个函数了
改一下缩进就可以了
建议把实例属性 stop 和 start 更改下,否则这个计时器调用一次就会导致函数 start 和 stop 函数被属性覆盖
参考代码:import time as t
class MyTimer():
# 开始计时
def start(self):
self.begin = t.localtime()
print('计时器开始计时')
#计时器停止计时
def stop(self):
self.end = t.localtime()
self.__calc()
print('计时器结束计时')
#内部方法,计算运行时间
def __calc(self):
self.lasted = []
self.prompt = '总共运行了'
for index in range(6):
self.lasted.append(self.end - self.begin)
self.prompt += str(self.lasted)
print(self.prompt) {:10_266:} 嗯好的,谢谢啦!
页:
[1]