Python 支持多态性吗
是的,Python支持多态性。多态性意味着拥有多个形式。多态性是Python类定义的一个重要特性,用于在类或子类之间具有相同命名的方法时的利用。
多态性可以通过继承来实现,在子类中使用基类方法或覆盖它们。
有两种类型的多态性
- 重载
- 覆盖
重载
当一个类中的两个或多个方法具有相同的方法名但参数不同时,发生重载。
覆盖
覆盖意味着在父类和子类中有两个具有相同方法名和参数(即方法签名)的方法。其中一个方法在父类中,另一个方法在子类中。
示例
class Fish():
def swim(self):
print("The Fish is swimming.")
def swim_backwards(self):
print("The Fish can swim backwards, but can sink backwards.")
def skeleton(self):
print("The fish's skeleton is made of cartilage.")
class Clownfish():
def swim(self):
print("The clownfish is swimming.")
def swim_backwards(self):
print("The clownfish can swim backwards.")
def skeleton(self):
print("The clownfish's skeleton is made of bone.")
a = Fish()
a.skeleton()
b = Clownfish()
b.skeleton()
输出
The fish's skeleton is made of cartilage.
The clownfish's skeleton is made of bone.