多态 #
多态允许不同类的对象对同一方法做出不同响应。
一、基本多态 #
python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Cow(Animal):
def speak(self):
return "Moo!"
def animal_sound(animal):
print(animal.speak())
# 同一函数处理不同类型
animal_sound(Dog()) # "Woof!"
animal_sound(Cat()) # "Meow!"
animal_sound(Cow()) # "Moo!"
二、鸭子类型 #
Python不检查类型,只检查行为。
python
class Duck:
def swim(self):
print("Duck swimming")
def quack(self):
print("Quack!")
class Person:
def swim(self):
print("Person swimming")
def quack(self):
print("I'm not a duck!")
def make_it_quack(thing):
thing.quack() # 只要能quack就行
make_it_quack(Duck()) # "Quack!"
make_it_quack(Person()) # "I'm not a duck!"
三、接口约定 #
python
class Shape:
def area(self):
raise NotImplementedError
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = 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
def total_area(shapes):
return sum(s.area() for s in shapes)
shapes = [Rectangle(2, 3), Circle(5)]
print(total_area(shapes)) # 6 + 78.5
四、运算符多态 #
python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # "(4, 6)"
五、总结 #
| 概念 | 说明 |
|---|---|
| 多态 | 同一接口不同实现 |
| 鸭子类型 | 关注行为而非类型 |
| 接口约定 | 约定必须实现的方法 |
| 运算符重载 | 特殊方法实现多态 |
最后更新:2026-03-16