Python 支持多态性吗?
programmingpythonserver side programming
是的,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.