python封装继承多态案例
时间: 2023-09-05 21:09:43 浏览: 118
一个实例告诉你什么是封装继承和多态
当然,我可以给你一些关于Python封装、继承和多态的案例。
封装的案例:
```python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
print(f"Driving {self.brand} {self.model}")
car = Car("Toyota", "Camry")
car.drive()
```
继承的案例:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Fido")
print(dog.speak())
cat = Cat("Whiskers")
print(cat.speak())
```
多态的案例:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def make_animal_speak(animal):
print(animal.speak())
dog = Dog("Fido")
cat = Cat("Whiskers")
make_animal_speak(dog)
make_animal_speak(cat)
```
希望这些案例能帮助你更好地理解Python的封装、继承和多态。如果还有其他问题,请随时提问。
阅读全文