关于python中子类继承父类init的三种方法
python
·
关于这个问题,一共有三种情况:
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
更多推荐
已为社区贡献1条内容
所有评论(0)