super 理解

  • super 解决了类继承时候,不同类的同名称方法继承问题

  • 当执行下面代码的时候,代码会报错’Girl’ object has no attribute ‘height’,

  • 两个类(Girl 和Person)有相同的方法名称,init 和about,当名称相同时候子类的方法会覆盖’父类’(这个父类的叫法有问题姑且这么叫)

  • 在子类Girl中,__init__方法已经覆盖父类的方法,

  • 当执行 E.about(‘Elisabeth’) ,这个about 是子类的about ,这个方法会用到height,但是这个功能在父类中的__init__的方法里面,不好意思被覆盖掉了,所以报错了


class Person:
    def __init__(self):
        self.height=180
    def about(self,name):
        print('from Person about++++{} , {} is about {}'.format('\n',name,self.height))
        
class Girl(Person):
    def __init__(self):
        
        
        self.age=16
        
    def about(self,name):
        print('from Girl about +++++{} , {} is a hot girl ,she is about {},and her age is {}'.format('\n',name,
    self.height,self.age))
        
    
    
if __name__=='__main__':
    E=Girl()
    E.about('Elisabeth') 

在子类Girl里面加上 super(Girl,self).init(),那么父类的__init__方法下移,子类的__init__方法继承了父类的功能

class Person:
    def __init__(self):
        self.height=180
    def about(self,name):
        print ('from Person about++++{} , {} is about {}'.format('\n',name,self.height))
        
class Girl(Person):
    def __init__(self):
        
        super(Girl,self).__init__()
        self.age=16
        
    def about(self,name):
        print('from Girl about +++++{} , {} is a hot girl ,she is about {},and her age is {}'.format('\n',name,
    self.height,self.age))
        
    
    
if __name__=='__main__':
    E=Girl()
    E.about('Elisabeth') 

可以看出现在这个方法还是Girl 里面的,因为子类的同名方法覆盖父类的方法

from Girl about +++++
 , Elisabeth is a hot girl ,she is about 180,and her age is 16

加载父类中的about方法

class Person:
    def __init__(self):
        self.height=180
    def about(self,name):
        print('from Person about++++{} , {} is about {}'.format('\n',name,self.height))
        
class Girl(Person):
    def __init__(self):
        
        super(Girl,self).__init__()
        self.age=16
        
    def about(self,name):
        
        super(Girl,self).about(name)
        print ('from Girl about +++++{} , {} is a hot girl ,she is about {},and her age is {}'.format('\n',name,
    self.height,self.age))
        
    
    
if __name__=='__main__':
    E=Girl()
    E.about('Elisabeth') 
from Person about++++
 , Elisabeth is about 180
from Girl about +++++
 , Elisabeth is a hot girl ,she is about 180,and her age is 16
posted @ 2022-08-19 22:51  luoganttcc  阅读(14)  评论(0)    收藏  举报