day15-面向对象作业2

  1. 定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积

    class Rectangle:
        def __init__(self, length, width):
            self.length = length
            self.width = width
    
        def getarea(self):
            return self.length * self.width
    
        def getperimeter(self):
            return 2 * (self.length + self.width)
    
        def showall(self):
            print("长:", self.length)
            print("宽:", self.width)
            print("面积:", self.getarea())
            print("周长:", self.getperimeter())
    
    
    a = Rectangle(10, 10)
    a.showall()
    
  2. 定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离

    class Point:
        def __init__(self, x=0, y=0):
            self.x = x
            self.y = y
    
        def distance(self, other):
            return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
    
    
    p1 = Point()
    p2 = Point(1, 3)
    print('两点距离:', p2.distance(p1))
    
  3. 定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切

    class Point:
        def __init__(self, x=0, y=0):
            self.x = x
            self.y = y
    
        def distance(self, other):
            return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
    
    
    class Circle:
        Pi = 3.14
    
        def __init__(self, r, center=Point(0, 0)):
            self.r = r
            self.center = center
    
        def perimeter(self):
            return 2 * Circle.Pi * self.r
    
        def area(self):
            return Circle.Pi * self.r ** 2
    
        def is_exterior_contact(self, other):
            return self.center.distance(other.center) == (self.r + other.r)
    
    
    c1 = Circle(5)
    
    print('该圆的周长为:', c1.perimeter())
    print('该圆的面积:', c1.area())
    c2 = Circle(5, Point(0, 10))
    print(c1.is_exterior_contact(c2))
    
  4. 定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度

    class Point:
        def __init__(self, x=0, y=0):
            self.x = x
            self.y = y
    
        def distance(self, other):
            return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
    
    
    class Line:
        def __init__(self, start: Point, end: Point):
            self.start = start
            self.end = end
    
        def length(self):
            return self.start.distance(self.end)
    
    
    l1 = Line(Point(0, 0), Point(200, 100))
    print('线段长度为:', l1.length())
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王薇蕴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值