欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

六、类练习题

程序员文章站 2022-05-19 13:32:31
...

练习1:定义一个类描述数字时钟

from time import sleep
class Clock():
    def __init__(self,hour,minute,seconds):
        self._hour = hour
        self._minute = minute
        self._seconds = seconds

    def run(self):
        self._seconds += 1
        if self._seconds == 60:
            self._seconds = 0
            self._minute += 1
            if self._minute == 60:
                self._minute = 0
                self._hour += 1
                if self._hour == 24:
                    self._hour =0

    def show(self):
        return ("%02d:%02d:%02d"%(self._hour,self._minute,self._seconds))

def main():
    clock = Clock(23,59,58)
    while True:
        print(clock.show())
        sleep(1)
        clock.run()



if __name__=="__main__":
    main()