继承与多态
掌握单继承/多重继承、super()、MRO 方法解析顺序、mixin
继承与多态
继承让你基于现有类创建新类,复用代码。多态让不同类对同一方法有不同的实现。
学完本章你将掌握: 单继承、super()、方法重写、多重继承、isinstance 检查。
一、基本继承
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} 发出声音")
class Dog(Animal):
def speak(self): # 重写父类方法
print(f"{self.name}:汪汪!")
class Cat(Animal):
def speak(self):
print(f"{self.name}:喵喵!")
for a in [Dog("旺财"), Cat("咪咪")]:
a.speak()
二、super() 调用父类
python
class Person:
def __init__(self, name, age):
self.name, self.age = name, age
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age) # 调用父类 __init__
self.grade = grade
s = Student("小明", 15, "初三")
print(f"{s.name},{s.age}岁,{s.grade}")
三、多态实战
python
class Shape:
def area(self): return 0
class Rectangle(Shape):
def __init__(self, w, h): self.w, self.h = w, h
def area(self): return self.w * self.h
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14 * self.r ** 2
shapes = [Rectangle(3,4), Circle(5)]
for s in shapes:
print(f"面积: {s.area()}")
四、isinstance 检查
python
d = Dog("旺财")
print(isinstance(d, Dog)) # True
print(isinstance(d, Animal)) # True(子类也是父类实例)
小结
class Child(Parent)继承super()调用父类方法- 重写方法实现多态
isinstance(obj, Class)检查类型