魔法方法,简单定制
哪位大神可以告诉我为啥总是提示在MyTime里面没有属性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)
====================================== RESTART: C:\Users\john\Desktop\time.py =====================================
>>> t1 = MyTimer()
>>> t1.start()
计时开始...
>>> t1.stop()
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
t1.stop()
File "C:\Users\john\Desktop\time.py", line 12, in stop
self.calc()
AttributeError: 'MyTimer' object has no attribute 'calc' 缩进问题,_calc()定义在stop()函数里面了 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) 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)
t1 = MyTimer()
t1.start()
t1.stop()
好像是你没对齐,把def _calc这个对齐了,就能运行 疾风怪盗 发表于 2020-8-28 19:55
好像是你没对齐,把def _calc这个对齐了,就能运行
还是我太蠢了,谢谢大佬{:5_110:} 南有暖树 发表于 2020-8-28 20:21
还是我太蠢了,谢谢大佬
问题解决了话,就设个最佳把求助帖关了吧,给你回复的几个,都很快就发现了你的代码的问题
页:
[1]