day18-面向对象作业

  1. 定义一个狗类和一个人类:

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

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

    class Dog:
        def __init__(self, name, gender, variety):
            self.name = name
            self.gender = gender
            self.variety = variety
        def howl(self):
            print(f'{self.name}在叫唤')
    
    d = Dog('旺财', '公', '柯基')
    d.howl()
    
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        def stroll(self, dog):
            print(f'{self.name}遛{dog.name}')
    
    
    p = Person('隔壁老王', '18')
    p.stroll(Dog('旺财', '公', '柯基'))
    
  2. 定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积

    class Rectangle:
        def __init__(self, length, width):
            self.length = length
            self.width = width
        def Perimeter(self):
            return self.width * 2 + self.length * 2
        def Area(self):
            return self.width * self.length
    r = Rectangle(10, 5)
    print(f'周长:{r.Perimeter()}, 面积:{r.Area()}')
    
  3. 定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离

    class Two:
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def Get_distance(self, point):
            g = ((self.x - point.x) ** 2 + (self.y - point.y) ** 2) ** 1/2
            return g
    t = Two(2, 3)
    print(f'两点间的距离为{t.Get_distance(Two(3, 7))}')
    
  4. 定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切

    pi = 3.1415926
    class Circle:
        def __init__(self, r, x, y):
            self.r = r
            self.x = x
            self.y = y
    
        def Perimeter(self):
            return 2 * pi * self.r
    
        def Area(self):
            return pi * self.r ** 2
    
        def Judge(self, point):
            g = ((self.x - point.x) ** 2 + (self.y - point.y) ** 2) ** 1 / 2
            gg = self.r + point.r
            if g == gg:
                return 'yes'
            else:
                return 'no'
    t = Circle(3, 2, 3)
    print(f'是否外切:{t.Judge(Circle(4, 3, 7))}')
    
  5. 定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度

    class Segment:
        def __init__(self, begin, end):
            self.begin = begin
            self.end = end
        def Get_length(self):
            return self.end - self.begin
    s = Segment(5, 10)
    s.Get_length()
    print(f'该线段长度为{s.Get_length()}')
    
上一篇:Day18.拷贝构造函数调用时机,深拷贝与浅拷贝


下一篇:java – System属性http.nonProxyHosts被设置为local | * .local …是什么意思?有什么影响?