Python学习笔记:方法重写的理解

方法的重写 如果你的基类(父类方法的功能不能满足你的需求派生类(子类中重写定义一个基类拥有的方法,调用时使用派生类中重写定义的方法。

 

当我们调用一个对象的方法时首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)

 

首先定义一个基类:

class Animal:
    def eat(self):
        print("小动物吃东西~~~")

    def run(self):
        print("小动物跑。。。")

 

不重写基类方法时:

class Animal:
    def eat(self):
        print("小动物吃东西~~~")

    def run(self):
        print("小动物跑。。。")

class Dog(Animal):
    def bark(self):
        print("小狗叫:汪汪汪...")

d = Dog()
d.run()

运行结果:小动物跑。。。

重写基类方法时:

class Animal:
    def eat(self):
        print("小动物吃东西~~~")

    def run(self):
        print("小动物跑。。。")

class Dog(Animal):
    def bark(self):
        print("小狗叫:汪汪汪...")

    def run(self):
        print("小狗跑~~~")
        
d = Dog()
d.run()

运行结果:小狗跑~~~

 

如果当基类和派生类中存在构造函数(__init__())时,派生类中的__init__()则是重写了基类中的构造函数。如下示例:

class Fruit:

    def __init__(self, color="绿色"):
        Fruit.color = color

    def harvest(self):
        print(f"水果原来是{Fruit.color}的!")


class Apple(Fruit):

    def __init__(self):
        print("我是苹果")

apple = Apple()
apple.harvest()

运行结果:

我是苹果
Traceback (most recent call last):
  File "F:/python/PycharmProjects/work/test_01.py", line 60, in <module>
    apple.harvest()
  File "F:/python/PycharmProjects/work/test_01.py", line 51, in harvest
    print(f"水果原来是{Fruit.color}的!")
AttributeError: type object 'Fruit' has no attribute 'color'

出现报错原因是Apple的构造函数__init__()重写了,新的构造函数里面没有color的属性的代码,为了是代码顺利运行,达到预期结果,就需要使派生类Apple中的构造函数调用基类Fruit中的构造函数来进行基本的初始化。

目前有两种方式:

  (1)调用基类构造函数的未绑定版本。

     在调用一个实例的方法时,该方法的self参数会被自动绑定到实例上(这称为绑定方法),但如果直接调用类的方法(比如Bird.__init__),就没有实例被绑定,这样的方法称为未绑定方法。

  (2)使用super函数。

     Super函数只能在新式类使用。当前类和对象可以作为super函数的参数使用,调用函数返回的对象的任何方法都是调用超类的方法,而不是当前类的方法。

 

 方式一:调用基类构造函数的未绑定版本

 

class Fruit:

    def __init__(self, color="绿色"):
        Fruit.color = color

    def harvest(self):
        print(f"水果原来是{Fruit.color}的!")


class Apple(Fruit):

    def __init__(self):
        print("我是苹果")
        Fruit.__init__(self)       # 调用基类构造函数的未绑定版本

apple = Apple()
apple.harvest()

运行结果:

我是苹果
水果原来是绿色的!

 

方法二:使用super函数

class Fruit:

    def __init__(self, color="绿色"):
        Fruit.color = color

    def harvest(self):
        print(f"水果原来是{Fruit.color}的!")


class Apple(Fruit):

    def __init__(self):
        print("我是苹果")
        super().__init__()        # 使用super()函数

apple = Apple()
apple.harvest()    

运行结果:

我是苹果
水果原来是绿色的!

 

posted @ 2020-07-30 15:55  piecesof  阅读(475)  评论(0编辑  收藏  举报