Python 中的方法覆盖

原文:https://www.studytonight.com/python/method-overriding-in-python

方法覆盖是面向对象编程的一个概念,它允许我们在子类中更改函数的实现,该子类在父类中定义。它是一个子类改变其父类(祖先)已经提供的任何方法的实现的能力。

覆盖函数必须满足以下条件:

  1. 传承 应该在那里。函数覆盖不能在类中完成。我们需要从父类派生一个子类。
  2. 在子类中重新定义的函数应该具有与父类相同的签名,即相同的参数数量

正如我们已经了解到的 继承 的概念,我们知道当一个子类继承一个父类时,它也可以访问它publicprotected ( 访问 python 中的修饰符 )变量和方法,例如,

# parent class
class Parent:
    # some random function
    def anything(self):
        print('Function defined in parent class!')

# child class
class Child(Parent):
    # empty class definition
    pass

obj2 = Child()
obj2.anything()

父类中定义的函数!

子类可以访问父类方法的同时,也可以为父类方法提供新的实现,称为方法覆盖


Python 方法覆盖示例

让我们举一个非常酷的例子,我们在继承教程中也有过。有一个名为Animal的父类:

class Animal:
    # properties
    multicellular = True
    # Eukaryotic means Cells with Nucleus
    eukaryotic = True

    # function breathe
    def breathe(self):
        print("I breathe oxygen.")

    # function feed
    def feed(self):
        print("I eat food.")

让我们创建一个子类Herbivorous,它将扩展类Animal:

class Herbivorous(Animal):

    # function feed
    def feed(self):
        print("I eat only plants. I am vegetarian.")

在子类Herbivorous中,我们已经覆盖了方法feed()

所以现在当我们创建一个类的对象Herbivorous并调用方法feed()时,被覆盖的版本将被执行。

herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()

我只吃植物。我是素食者。我呼吸氧气。

点击运行查看正在运行的代码,并随时对其进行更改,然后再次运行。