python 父类方法重写

限于喜欢 提交于 2020-01-22 19:26:10
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参数赋值。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!