class Father(object):
def __init__(self, name):
self.name=name
print ("name: %s" %( self.name))
def getName(self):
return'Father ' + self.name
class Son(Father):
def getName(self):
return'Son '+self.name
if __name__=='__main__':
son=Son('runoob')
print ( son.getName())
2.子类重写了父类的__init__ 时,实例化子类,就不会调用父类已经定义的__init__
class Father(object):
def __init__(self, name):
self.name=name
print ("name: %s" %( self.name))
def getName(self):
return'Father ' + self.name
class Son(Father):
def __init__(self, name):
print ("hi")
self.name = name
def getName(self):
return'Son '+self.name
if __name__=='__main__':
son=Son('runoob')
print ( son.getName())
3.如果子类重写了父类的普通方法时,要继承父类的同名方法,可以使用 super 关键字
方法一:super(子类,self).方法名(参数1,参数2,…)
方法二:父类名称.方法名(self,参数1,参数2,…)
class Father:
def hello(self):
print("father")
class Child(Father):
def hello(self):
super(Child,self).hello()#Father.hello(self)
print("son")
c = Child()
c.hello()