|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
小甲鱼在计时器那题的代码- import time as t
- class Timer():
- def __init__(self):
- self.unit=['年','月','天','小时','分钟','秒']
- self.prompt='未开始计时'
- self.lasted=[]
- self.begin=0
- self.end=0
- def __str__(self):
- return self.prompt
- __rept__=__str__
- def __add__(self,other):
- prompt='总共运行了'
- result=[]
- for index in range(6):
- result.append(self.lasted[index]+other.lasted[index])
- if result[index]!=0:
- prompt+=(str(result[index])+self.unit[index])
- 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.__calulate()
- print('计时结束了嗷')
- def __calulate(self):
- self.lasted=[]
- self.prompt='总共运行了'
- for index in range(6):
- self.lasted.append(self.end[index]-self.begin[index])
- if self.lasted[index]!=0:
- self.prompt+=(str(self.lasted[index])+self.unit[index])
-
复制代码
有几个地方不是很懂
让t1=Timer()
1为什么打出t1就能输出self.prompt内的内容 是因为__str__这个方法吗 __str__不是要调用str时才触发吗这里没有调用啊 而且后面那个__rept__=__str__ 这个东西是啥意思怎么还可以这样搞??
2另外就是在stop()方法中有个 if not self.begin 是啥意思没见过这样的表达额
3最后就是对于self.xx中的xx是指实例对象的属性吗 还是属性和方法都能表示??
1. 在 Shell 中直接输入一个变量会打印该变量 __repr__ 后的结果,__repr__ = __str__ 是函数间的赋值,意思是把 __str__ 的所有功能都赋值给 __repr__
2. not self.begin 是独立的表达式,当 self.begin 为 0 时 not self.begin 为 True
3. 属性和方法都能表示
|
|