鱼C论坛

 找回密码
 立即注册
查看: 2158|回复: 2

[已解决]魔法方法:简单定制 问题求助

[复制链接]
发表于 2020-11-27 15:29:30 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在看小甲鱼的第44讲,制作一个计时器,代码如下:

import time as t

class MyTimer():
    #开始计时
    def start(self):
        self.start1 = t.localtime()
        print('Timing starts')

    #结束计时
    def stop(self):
        self.stop1 = t.localtime()
        self.total()
        print('Timing stops')

    #计时计算
    def total(self):
        self.last = []
        self.prompt = 'It\'s '
        for each in range[6]:
            self.last.append(self.stop1[each]-self.start1[each])
            self.prompt += str(self.last[each])

        print(self.prompt)


运行之后,报错:

>>> t = MyTimer()
>>> t.start()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    t.start()
  File "F:\Programming\Python\practice\44.0.py", line 6, in start
    self.start1 = t.localtime()
AttributeError: 'MyTimer' object has no attribute 'localtime'

求大佬解答!
最佳答案
2020-11-27 15:38:38
对象名和里面的time模块的别名冲突了
  1. t1 = MyTimer()
  2. t1.start()
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-11-27 15:38:38 | 显示全部楼层    本楼为最佳答案   
对象名和里面的time模块的别名冲突了
  1. t1 = MyTimer()
  2. t1.start()
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-11-27 15:48:50 | 显示全部楼层
两个问题
首先变量名污染
你开头引用import time as t
后面 t = MyTimer()
t就失去了他的time属性
另外第十九行for each in range[6] 改为for each in range(6)
附源码
  1. import time as t

  2. class MyTimer():
  3.     #开始计时
  4.     def start(self):
  5.         self.start1 = t.localtime()
  6.         print('Timing starts')

  7.     #结束计时
  8.     def stop(self):
  9.         self.stop1 = t.localtime()
  10.         self.total()
  11.         print('Timing stops')

  12.     #计时计算
  13.     def total(self):
  14.         self.last = []
  15.         self.prompt = 'It\'s '
  16.         for each in range(6):
  17.             self.last.append(self.stop1[each]-self.start1[each])
  18.             self.prompt += str(self.last[each])

  19.         print(self.prompt)
复制代码
  1. >>> a=MyTimer()
  2. >>> a.start()
  3. Timing starts
  4. >>> a.stop()
  5. It's 000008
  6. Timing stops
  7. >>> t=MyTimer()
  8. >>> t.start()
  9. Traceback (most recent call last):
  10.   File "<pyshell#19>", line 1, in <module>
  11.     t.start()
  12.   File "C:\Users\admin\Desktop\f1.py", line 6, in start
  13.     self.start1 = t.localtime()
  14. AttributeError: 'MyTimer' object has no attribute 'localtime'
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-30 08:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表