python class Car: def __init__(self, brand, model, color): self.brand = brand self.model = model self.color = color def drive(self): print(f"Driving {self.color} {self.brand} {self.model}") my_car = Car("Tesla", "Model S", "Red") my_car.drive() python class Animal: def __init__(self, name): self.name = name def speak(self): pass class Dog(Animal): def speak(self): print(f"{self.name} says 'Woof!'") class Cat(Animal): def speak(self): print(f"{self.name} says 'Meow!'") my_dog = Dog("Buddy") my_cat = Cat("Whiskers") my_dog.speak() my_cat.speak() python class Shape: def area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2 my_rectangle = Rectangle(5, 3) my_circle = Circle(2) print(f"Area of rectangle: {my_rectangle.area()}") print(f"Area of circle: {my_circle.area()}")


上一篇:
下一篇:
切换中文