Python_类的继承与方法重写

python学习网 2019-10-16 20:30:01

1.新建子类时,括号内要传入继承的父类名

2.super()方法:自动寻找当前类的父类,并调用父类的构造函数,初始化属性值

class Cup:

    #构造函数,初始化属性值
    def __init__(self,capacity,color):
        self.capacity=capacity
        self.color=color

    def retain_water(self):
        print("杯子颜色:"+self.color+",杯子容量:"+self.capacity+",正在装水.")

    def keep_warm(self):
        print("杯子颜色:"+self.color+",杯子容量:"+self.capacity+",正在保温.")

class Luminous_Cup(Cup):

    #构造函数,调用父类的构造函数初始化属性值
    def __init__(self,capacity,color):
        super().__init__(capacity,color)

    def glow(self):
        print("我正在发光...")


currentCup=Luminous_Cup('300ml','翠绿色')
currentCup.retain_water()
currentCup.glow()

 3.方法重写:

class Cup:

    #构造函数,初始化属性值
    def __init__(self,capacity,color):
        self.capacity=capacity
        self.color=color

    def retain_water(self):
        print("杯子颜色:"+self.color+",杯子容量:"+self.capacity+",正在装水.")

    def keep_warm(self):
        print("杯子颜色:"+self.color+",杯子容量:"+self.capacity+",正在保温.")

class Luminous_Cup(Cup):

    #构造函数,调用父类的构造函数初始化属性值
    def __init__(self,capacity,color):
        super().__init__(capacity,color)

    #方法重写
    def retain_water(self):
        print("杯子颜色:"+self.color+",杯子容量:"+self.capacity+",正在装水,正在发光...")

    def glow(self):
        print("我正在发光...")


currentCup=Luminous_Cup('300ml','翠绿色')
#调用子类中的retain_water()方法
currentCup.retain_water()
#调用父类中的retain_water()方法
super(Luminous_Cup,currentCup).retain_water()

 

阅读(2776) 评论(0)