使用super函数----增量重写普通方法和构造方法

使用super函数----增量重写普通方法和构造方法

在子类中如果重写了超类的方法,通常需要在子类方法中调用超类的同名方法,也就是说,重写超类的方法,实际上应该是一种增量的重写方式,子类方法会在超类的同名方法的基础上

做一些其他的工作。

如果在子类中要访问超类中的方法,需要使用super函数。该函数返回的对象代表超类对象,所以访问super函数返回的对象中的资源都属于超类。super函数可以不带任何参数,

也可以带两个参数,第一个参数表示当前类的继承,第2个参数需要传入self。


本例中Bird类是Animal类的子类。在Bird类的构造方法中通过super函数调用了Animal类的构造方法。在SonBird类的构造方法中通过super函数调用了Bird类的构造方法


class Animal:
    def __init__(self):
        print("Animal init")
class Bird(Animal):
    # 为Bird类的构造方法增加一个参数(hungry)
    def __init__(self,hungry):
        # 调用Animal类的构造方法
        super().__init__()
        self.hugry=hungry
    def eat(self):
        if self.hugry:
            print("已经吃了虫子!")
        else:
            print("已经超过饭了,不饿了")
b=Bird(False)
b.eat()
b.eat()

class SonBird(Bird):
    def __init__(self,hungry):
        # 调用Bird类的构造方法,如果为super函数指定参数,第1个参数需要是当前类的类型(SonBird)
        super(SonBird,self).__init__(hungry)
        self.sound='向天再借500年'
    def sing(self):
        print(self.sound)

a=SonBird(True)
a.sing()
a.eat()


Animal init
已经超过饭了,不饿了
已经超过饭了,不饿了
Animal init
向天再借500年
已经吃了虫子!
原文地址:https://www.cnblogs.com/effortsing/p/10388186.html