python 父类方法重写

class Bird:
    def isWing(self):
        print("鸟有翅膀")
    def fly(self):
        print("鸟会飞")
class Ostrich(Bird):
    def fly(self):
        print("鸵鸟不会飞")
ostrich = Ostrich()
ostrich.fly()
鸵鸟不会飞

如何调用被重写的方法

事实上,如果我们在子类中重写了从父类继承来的类方法,那么当在类的外部通过子类对象调用该方法时,python总是会执行子类中的重写的方法。

class Bird:
    def isWing(self):
        print("鸟有翅膀")
    def fly(self):
        print("鸟会飞")
class Ostrich(Bird):
    def fly(self):
        print("鸵鸟不会飞")
ostrich = Ostrich()
#调用 Bird 类中的 fly() 方法
Bird.fly(ostrich)
#通过类名调用实例方法的这种方式,又被称为未绑定方法。
鸟会飞

注意:使用类名调用其类方法,python不会为该方法的第一个self参数自动绑定值,因此采用这种调用方法,需要手动为self参数赋值。

原文地址:https://www.cnblogs.com/xiaobaizzz/p/12229354.html