Python基础:类的继承(super().__init__)

一个简单的例子,包括了父类的创建,子类的继承,子类构造方法的书写,和子类对父类方法的重写。

其中Animal是父类,Human是子类,在实现Human的_init_()方法时,调用父类的构造方法,既可以使用
Animal.__init__(name,feature)
也可以使用super().__init__(name,feature)
推荐第二种写法

class Animal(object):
    def __init__(self,name,feature):
        self.name = name
        self.feature = feature

    def eat(self):
        print('animal eat things')

    def walking(self):
        print('animal can walking..')


class Human(Animal):
    def __init__(self,name,feature,food):
        # 先继承父类的构造方法,再增加自己的
        super().__init__(name,feature)
        self.food = food


    def eat(self):
        # 重写父类的方法
        print('human eat everything...')

猜你喜欢

转载自blog.csdn.net/ninnyyan/article/details/80764097