构造函数
析构函数
所有指向该对象的引用都被删除时,析构函数调用
魔法方法是指Python内部已经包含的,被双下划线所包围的方法,这些方法在进行特定的操作时会自动被调用
打印类
# -*- coding: utf-8 -*-
"""
Created on Sun May 12 15:03:21 2019
@author: Administrator
"""
import time as t
class MyTimer():
def __init__(self):
self.prompt="未开始计时,请先调用start方法开始计时"
self.begin=0
self.end=0
self.last=[]
self.result=[]
self.unit=['年','月','天','时','分','秒']
##############重写print##################
def __str__(self):
return self.prompt
__repr__=__str__
#################################
def __add__(self,other):
self.prompt="总共运行了"
for index in range(6):
self.result.append(self.last[index]+other.last[index])
if self.result[index]:
self.prompt=self.prompt+str(self.result[index])+str(self.unit[index])
return self.prompt
def start(self):
self.begin=t.localtime()
self.prompt="请先调用stop方法结束计时"
print("计时开始......")
def stop(self):
if not self.begin:
self.prompt="请先调用start方法开始下一轮计时"
else:
self.end=t.localtime()
self.calculate()
print("计时结束......")
def calculate(self):
self.last=[]
self.prompt="总共运行了"
for index in range(6):
self.last.append(self.end[index]-self.begin[index])
if self.last[index]:
self.prompt=self.prompt+str(self.last[index])+str(self.unit[index])
属性访问
迭代器
生成器