Section 100.1: 基本方法的覆盖

下面是一个 Python 中基本重载的示例(为了清晰和与 Python 2 和 Python 3 兼容,使用了 new style class 和 print with()):

class Parent(object):
  def introduce(self):
    print("Hello!")

  def print_name(self):
    print("Parent")

class Child(Parent):
  def print_name(self):
    print("Child")

p = Parent()
c = Child()

p.introduce()
p.print_name()

c.introduce()
c.print_name()
$ python basic_override.py
Hello!
Parent
Hello!
Child

基本方法的覆盖

创建子类时,它会继承父类的方法。这意味着父类拥有的任何方法,子类也将拥有。在本例中,尽管在 Child 的类定义中没有明确定义 introduce,但它是为子类定义的,因为它是为 Parent 定义的。

在本例中,覆盖发生在 Child 定义了自己的 print_name 方法时。如果没有声明该方法,c.print_name() 将打印Parent。但是,子类覆盖了父类对 print_name 的定义,因此现在调用 c.print_name() 时,将打印“子代”。