|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Twilight6 于 2020-7-13 21:42 编辑
代码如下:
- import time as t
- class Mytimer():
- def __str__(self):
- return self.prompt
- __repr__=__str__
- def begin(self):
- self.start=t.localtime()
- print("现在开始计时")
- def end(self):
- self.stop=t.localtime()
- self.calc()
- print("计时结束")
- def calc(self):
- self.lasted=[]
- self.prompt="总共运行了"
- for i in range(6):
- self.lasted.append(self.stop[i]-self.start[i])
- self.prompt+=str(self.lasted[i])
复制代码
这时候运行代码:
w=Mytimer()
w.begin()
w.stop
然后print(w),显示:总共运行了0000012
或者我直接w, 显示:总共运行了0000012.
为什么显示结果一样?__str__跟__init__一样,在类实例时被自动调用吗?
所以你直接 w 时候是调用了__repr__ 魔法方法,而 __repr__魔法方法被赋值为 __str__ 则此时调用的还是 __str__ 方法
所以这个时候你 print(w) 和直接 w 都是一样的,最终都是调用了 __str__
|
|