天天看點

Day17面向對象作業

  1. 定義一個矩形類,擁有屬性:長、寬 擁有方法:求周長、求面積
    class Rectangle:
        def __init__(self, length, width):
            self.length = length
            self.width = width
    
        def perimeter(self):
            return (self.length + self.width) * 2
    
        def area(self):
            return self.length * self.width
    
    
    a1 = Rectangle(10, 20)
    print('周長', a1.perimeter())
    print('面積', a1.area())
               
  2. 定義一個二維點類,擁有屬性:x坐标、y坐标 擁有方法:求目前點到另外一個點的距離
    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def length(self, other):
            return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** (0.5)
    
    
    p1 = Point(4, 5)
    p2 = Point(1, 1)
    print(p1.length(p2))
               
  3. 定義一個圓類,擁有屬性:半徑、圓心 擁有方法:求圓的周長和面積、判斷目前圓和另一個圓是否外切
    class Circle:
        def __init__(self, r, center=Point(0, 0)):
            self.r = r
            self.center = center
    
        def is_exterior_contact(self, other):
            return self.r + other.r == self.center.length(other.center)
    
    
    c1 = Circle(10)
    c2 = Circle(20, Point(30, 0))
    result = c1.is_exterior_contact(c2)
    print(result)
               
  4. 定義一個線段類,擁有屬性:起點和終點, 擁有方法:擷取線段的長度
    class Line:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def length(self, other):
            return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
    
    
    a1 = Line(0, 0)
    a2 = Line(3, 4)
    print('線段的長度:', a1.length(a2))
               
  5. 定義一個狗類和一個人類:

    狗擁有屬性:姓名、性别和品種 擁有方法:叫喚

    人類擁有屬性:姓名、年齡、狗 擁有方法:遛狗

    class Dog:
        def __init__(self, name, gender, breed):
         self.name = name
            self.gender = gender
            self.breed = breed
    
        def cry(self):
            return f'名叫{self.name}的會汪汪汪的{self.gender}{self.breed}'
    
    
    d1 = Dog('旺财', '公狗', '哈士奇')
    d1.cry()
    
    
    class Mankind:
        def __init__(self, name, age, dog):
            self.name = name
            self.age = age
            self.dog = dog
    
        def walkDog(self):
            return f'{self.age}歲的{self.name}在溜' + self.dog.cry()
    
    
    p1 = Mankind('小李', 18, d1)
    print(p1.walkDog())