鱼C论坛

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

[已解决]python 类 的问题

[复制链接]
发表于 2021-1-28 23:15:27 | 显示全部楼层 |阅读模式

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

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

x
  1. import time as t

  2. class MyTimer:
  3.     def __init__(self):
  4.         self.unit = ['年', '月', '天', '小时', '分钟', '秒']
  5.         self.prompt = "未开始计时!"
  6.         self.lasted = []
  7.         self.begin = 0
  8.         self.end = 0
  9.    
  10.     def __str__(self):
  11.         return self.prompt

  12.     __repr__ = __str__

  13.     def __add__(self, other):
  14.         prompt = "总共运行了"
  15.         result = []
  16.         for index in range(6):
  17.             result.append(self.lasted[index] + other.lasted[index])
  18.             if result[index]:
  19.                 prompt += (str(result[index]) + self.unit[index])
  20.         return prompt
  21.    
  22.     # 开始计时
  23.     def start(self):
  24.         self.begin = t.localtime()
  25.         self.prompt = "提示:请先调用 stop() 停止计时!"
  26.         print("计时开始...")

  27.     # 停止计时
  28.     def stop(self):
  29.         if not self.begin:
  30.             print("提示:请先调用 start() 进行计时!")
  31.         else:
  32.             self.end = t.localtime()
  33.             self._calc()
  34.             print("计时结束!")

  35.     # 内部方法,计算运行时间
  36.     def _calc(self):
  37.         self.lasted = []
  38.         self.prompt = "总共运行了"
  39.         for index in range(6):
  40.             self.lasted.append(self.end[index] - self.begin[index])
  41.             if self.lasted[index]:
  42.                 self.prompt += (str(self.lasted[index]) + self.unit[index])
  43.         # 为下一轮计时初始化变量
  44.         self.begin = 0
  45.         self.end = 0
复制代码

为什么__add__方法下的prompt、result前不加self
最佳答案
2021-1-29 09:12:42
他们两个不是类里面的成员变量,为是为了再__add__函数中实现计时用的局部变量,退出函数后就消失了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-1-28 23:51:20 | 显示全部楼层
因为那是局部变量。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-1-29 09:12:42 | 显示全部楼层    本楼为最佳答案   
他们两个不是类里面的成员变量,为是为了再__add__函数中实现计时用的局部变量,退出函数后就消失了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-26 15:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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