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.
广告