关于这个问题,一共有三种情况:

1、子类不重写init,继承父类init

2、子类重写init, 不继承父类init

3、子类重写init,同时继承父类init(super关键字)

情况一:(子类不重写init,继承父类init)

代码:

class Father(object):
    def __init__(self, name):
        self.name = name
        print("name: %s" % self.name)

    def Get_Name(self):
        return 'Father ' + self.name


class Son(Father):
    def get_name(self):
        return 'Son '+self.name


if __name__ == '__main__':
    son = Son('I am here')
    print(son.get_name())

结果:

name: I am here
Son I am here

 情况二:(子类重写init, 不继承父类init)

代码:

class Father(object):
    def __init__(self, name):
        self.name = name
        print("name: %s" % self.name)

    def Get_Name(self):
        return 'Father ' + self.name


class Son(Father):
    def __init__(self, name):
        print("hi")
        self.name = name

    def get_name(self):
        return 'Son '+self.name


if __name__ == '__main__':
    son = Son('I am here')
    print(son.get_name())

结果:

hi
Son I am here

 情况三:(子类重写init,同时继承父类init(super关键字))

 如果重写了__init__ 时,要继承父类的构造方法,可以使用 super 关键字:

写法一:super(子类名称,self).init(参数1,参数2,…)

写法二:父类名称.init(self,参数1,参数2,…)

class Father(object):
    def __init__(self, name):
        self.name = name
        print("name: %s" % self.name)

    def Get_Name(self):
        return 'Father ' + self.name


class Son(Father):
    def __init__(self, name):
        super(Son, self).__init__(name)
        print("hi")
        self.name = name

    def get_name(self):
        return 'Son '+self.name


if __name__ == '__main__':
    son = Son('I am here')
    print(son.get_name())

结果:

name: I am here
hi
Son I am here
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐