class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print('Woof')
class Cat(Animal):
def speak(self):
print('Meow')
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()
继承的体现
Dog
类:Dog
类继承自Animal
类,这意味着Dog
类拥有Animal
类的所有属性和方法(在本例子中是speak
方法,虽然Animal
类的speak
方法是一个占位方法)。Dog
类通过class Dog(Animal)
语句明确声明继承关系,这样Dog
类就成为了Animal
类的子类。
Cat
类:同理,Cat
类也继承自Animal
类,通过class Cat(Animal)
语句,Cat
类也获得了Animal
类的相关属性和方法。
多态的体现
- 方法重写:
Dog
和Cat
类都重写了从Animal
类继承来的speak
方法,各自实现了不同的行为,Dog
类的speak
方法输出'Woof',Cat
类的speak
方法输出'Meow'。
- 动态绑定:当创建
Dog
和Cat
的实例dog
和cat
,并调用它们的speak
方法时,Python会根据对象的实际类型(运行时类型)来决定调用哪个speak
方法。虽然dog
和cat
都可以看作是Animal
类型(因为它们继承自Animal
),但在运行时,dog.speak()
会调用Dog
类中重写的speak
方法,cat.speak()
会调用Cat
类中重写的speak
方法。这就是多态的体现,同样的方法调用(speak
方法),根据对象的不同类型,产生不同的行为。