面对对象编程基础之练习

七、练习

1.定义一个类描述数字时钟

from time import sleep
import os

class Clock(object):
    def __init__(self,hour=0,minute=0,second=0):#初始化方法
        self.hour=hour
        self.minute=minute
        self.second=second

    def run(self):  #走字
        self.second+=1
        if self.second==60:
            self.second=0
            self.minute+=1
            if self.minute==60:
                self.minute=0
                self.hour+=1
                if self.hour==24:
                    self.hour=0
  
    def show(self): #显示
        print("{}时{}分{}秒".format(self.hour,self.minute,self.second))


def main():
    clock=Clock(23,59,58)
    while True:
        clock.show()
        sleep(1)
        clock.run()
        # os.system("cls")    #清屏
main()

在这里插入图片描述

2.定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法

from math import sqrt


class Point(object):
    def __init__(self, x=0, y=0):
        """ 初始化方法

        :param x: 横坐标
        :param y: 纵坐标
        """
        self.x = x
        self.y = y


    def move_to(self, x, y):

        """移动到指定位置

        :param x: 新的横坐标
        "param y: 新的纵坐标
        """

        self.x = x
        self.y = y


    def move_by(self, dx, dy):

        """移动指定的增量

        :param dx: 横坐标的增量
         "param dy: 纵坐标的增量
        """

        self.x += dx
        self.y += dy


    def distance_to(self, other):

        """计算与另一个点的距离
        :param other: 另一个点
         """
        dx = self.x - other.x
        dy = self.y - other.y
        return sqrt(dx ** 2 + dy ** 2)

    def __str__(self):
        return '(%s, %s)' % (str(self.x), str(self.y))


def main():
    p1 = Point(3, 5)
    p2 = Point()
    print(p1)
    print(p2)
    p2.move_by(-1, 2)
    print(p2)
    print(p1.distance_to(p2))


if __name__ == '__main__':
    main()

在这里插入图片描述

发布了134 篇原创文章 · 获赞 16 · 访问量 6337

猜你喜欢

转载自blog.csdn.net/weixin_46108954/article/details/104646917
今日推荐