super在子类中使用,直接在代码中演示
- 先定义一个类,使用另一个类继承它,同时实例化并调用:
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
print('child')
c = FooChild() #在没有初始化父类时,只调用子类的初始化内容
c.bar('test') # 在没有初始化父类时,只调用父类的对象
print(c.parent)# 没有初始化时不能调用父类的属性
运行得到结果:
由此可以看出,如果在子类中不初始化父类 就不能调用父类中的属性,但是可以调用父类的方法.
下面使用super初始化父类:
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
super(FooChild,self).__init__()
print('child')
c = FooChild()
c.bar('test')
print(c.parent)
得到运行结果:
此处的"Parent"是由于初始化了父类,在实例化时就也输出了父类中的内容,同时也可以调用父类的bar方法
- 下面在子类加上与父类名称相同的方法,同时在子类调用父类的方法:
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
super(FooChild,self).__init__()
print('child')
def bar(self,message):
print ('Child bar fuction')
print (self.parent)
c = FooChild()
c.bar('test')
# 由于在子类的方法中调用了self.parent,这里就不再调用了
运行:
对比上面的结果,由于在子类加入了bar方法,在调用时又没有初始化父类的此方法,所以只调用了子类的方法
接着在子类中初始化父类的对应的方法:
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
super(FooChild,self).__init__()
print('child')
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
c = FooChild()
c.bar('test')
现在效果就有了,在调用bar()时,先调用了父类的方法,又调用了子类的方法
- 最后一种情况,如果不在子类的初始化中初始化父类,就会有以下结果:
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
# p = FooParent()
# print(p.parent)
# p.bar('hahahah')
class FooChild(FooParent):
def __init__(self):
# super(FooChild,self).__init__()
print('child')
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
# print (self.parent) #把它注释是因为不初始化父类的话,这里肯定会报错
c = FooChild()
c.bar('test')
此时调用了父类和子类的bar,但是只输出了子类的初始化内容
总结:在继承时,子类若想使用父类的某些功能,需要在对应的模块使用super对父类进行初始化.