-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: """ 狗狗 """ def __init__(self, name: str, gender: str, breed: str): self.name = name self.gender = gender self.breed = breed def bark(self): print(f'{self.name}: 汪汪...') class Person: """ 人类 """ def __init__(self, name: str, age: int, dog: Dog): self.name = name self.age = age self.dog = dog def walk_dog(self): print(f'{self.name}正在遛一条叫{self.dog.name}的狗狗') self.dog.bark() if __name__ == '__main__': my_dog = Dog("小黑", "公", "土狗") person1 = Person('小明', 18, my_dog) person1.walk_dog() # 小明正在遛一条叫小黑的狗狗 # 小黑: 汪汪...
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle: def __init__(self, long: float, wide: float): self.long = long self.wide = wide def perimeter(self) -> float: return 2*self.long + 2*self.wide def area(self) -> float: return self.long * self.wide if __name__ == '__main__': rec = Rectangle(10, 12) print(f'周长{rec.perimeter()}') print(f'面积{rec.area()}') # 周长44 # 面积120
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point: def __init__(self, x, y): self.x = x self.y = y def distance_another_point(self, another_point): return Point.two_point_distance(self, another_point) def __repr__(self): return str((self.x, self.y)) @staticmethod def two_point_distance(point1, point2): return Point.two_point_distance_square(point1, point2) ** 0.5 @staticmethod def two_point_distance_square(point1, point2): return ((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2) if __name__ == '__main__': point1 = Point(14, 36) point2 = Point(-23, 41) print(f'point1和point2的距离是{point1.distance_another_point(point2)}') print(f'point1和point2的距离是{Point.two_point_distance(point1, point2)}')
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
import math class Circle: pi = math.pi def __init__(self, radius, center: Point): self.radius = radius self.center = center def perimeter(self): return 2 * self.pi * self.radius def area(self): return self.pi * self.radius**2 def is_excircle_another_circle(self, another_circle): return Circle.is_two_circle_excircle(self, another_circle) def __repr__(self): return f"<{str(self.__class__)[1:-1]} {str(self.__dict__)[1:-1]}>" @staticmethod def is_two_circle_excircle(circle1, circle2): center_distance = Point.two_point_distance_square(circle1.center, circle2.center) sum_radius = (circle1.radius + circle2.radius) ** 2 if center_distance == sum_radius: return True else: return False if __name__ == '__main__': circle1 = Circle(8, Point(12, 34)) circle2 = Circle(3, Point(-10, 23)) if circle1.is_excircle_another_circle(circle2): print(f'{circle1}和{circle2}外切') else: print(f'{circle1}和{circle2}不外切')
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class LineSegment: def __init__(self, start, end): self.start = start self.end = end def length(self): return self.end - self.start if __name__ == '__main__': line = LineSegment(10, 30) print(f'line的长度是{line.length()}')