3.25面向对象作业

3.25面向对象基础

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

    class Rectangle:
        def __init__(self,length=0,width=0):
            self.length = length
            self.width = width
            def perimeter(self):
                print('矩形的周长为:',(self.length+self.width)<<1)
            def area(self):
                 print('矩形的面积为:',self.length*self.width)
    
    r = Rectangle(2,5)
    r.perimeter()
    r.area()
    
  2. 定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离

    import math
    
    class Point:
        def __init__(self, x=0, y=0):
            self.x = x
            self.y = y
        def distance(self, other):
            removing = math.hypot(self.x-other.x, self.y-other.y)
            print('两点之间的距离为:', removing)
    
    p1 = Point(9, 6)
    p2 = Point(3, 12)
    p2.distance(p1)
    
  3. 定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切

    class Round:
        def __init__(self, r, x=0, y=0):
            self.x = x
            self.y = y
            self.radius = r
        def perimeter(self):
            print('圆的周长为:', (self.radius << 1) * math.pi)
        def area(self):
            print('圆的面积为:', math.pow(self.radius, 2) * math.pi)
        def outside(self, other):
            distancec = math.hypot(self.x-other.x, self.y-other.y)
            if distancec == self.radius + other.radius:
                print('外切')
            else:
                print('不外切')
    
    o1 = Round(6)
    o2 = Round(y=3,r=1)
    o3 = Round(x=4,r=2)
    o1.perimeter()
    o2.area()
    o1.outside(o2)
    o1.outside(o3)
    
  4. 定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度

    class Line:
        def __init__(self, A, B):
            self.starting = A
            self.ending = B
        def lenght(self):
            print('线段长度为:', math.hypot(self.starting.x-self.ending.x, self.starting.y-self.ending.y))
    
    
    l = Line(p1, p2)
    l.lenght()
    
  5. 定义一个狗类和一个人类:

    狗拥有属性:姓名、性别和品种 拥有方法:叫唤

    人类拥有属性:姓名、年龄、狗 拥有方法:遛狗

    class Dog:
        def __init__(self, name, sex, variety):
            self.name = name
            self.sex = sex
            self.variety = variety
        def barking(self):
            print(f'名叫{self.name}的{self.sex}{self.variety}会Wang!Wang!Wang!叫的狗')
    
    d1 = Dog('honey', '雌性', '金毛')
    d1.barking()
    
    
    class Person:
        def __init__(self, name, age, dog):
            self.name = name
            self.age = age
            self.dog = dog
        def walk_dog(self):
            print(f'今年{self.age}岁的{self.name}在溜他', end='')
            self.dog.barking()
    
    
    p1 = Person('小珍', 22, d1)
    p1.walk_dog()
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值