class Bird: #鸟有翅膀 def isWing(self): print("鸟有翅膀") #鸟会飞 def fly(self): print("鸟会飞")但是,对于鸵鸟来说,它虽然也属于鸟类,也有翅膀,但是它只会奔跑,并不会飞。针对这种情况,可以这样定义鸵鸟类:
class Ostrich(Bird): # 重写Bird类的fly()方法 def fly(self): print("鸵鸟不会飞")可以看到,因为 Ostrich 继承自 Bird,因此 Ostrich 类拥有 Bird 类的 isWing() 和 fly() 方法。其中,isWing() 方法同样适合 Ostrich,但 fly() 明显不适合,因此我们在 Ostrich 类中对 fly() 方法进行重写。
在上面 2 段代码的基础上,添加如下代码并运行:重写,有时又称覆盖,是一个意思,指的是对类中已有方法的内部实现进行修改。
class Bird: #鸟有翅膀 def isWing(self): print("鸟有翅膀") #鸟会飞 def fly(self): print("鸟会飞") class Ostrich(Bird): # 重写Bird类的fly()方法 def fly(self): print("鸵鸟不会飞") # 创建Ostrich对象 ostrich = Ostrich() #调用 Ostrich 类中重写的 fly() 类方法 ostrich.fly()运行结果为:
鸵鸟不会飞
显然,ostrich 调用的是重写之后的 fly() 类方法。class Bird: #鸟有翅膀 def isWing(self): print("鸟有翅膀") #鸟会飞 def fly(self): print("鸟会飞") class Ostrich(Bird): # 重写Bird类的fly()方法 def fly(self): print("鸵鸟不会飞") # 创建Ostrich对象 ostrich = Ostrich() #调用 Bird 类中的 fly() 方法 Bird.fly(ostrich)程序运行结果为:
鸟会飞
此程序中,需要大家注意的一点是,使用类名调用其类方法,Python 不会为该方法的第一个 self 参数自定绑定值,因此采用这种调用方法,需要手动为 self 参数赋值。通过类名调用实例方法的这种方式,又被称为未绑定方法。
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有