zoukankan      html  css  js  c++  java
  • 类的继承

    继承是面向对象的三大特征之一,一个子类可以同时继承多个直接父类。

    继承的语法

    class SubClass(SuperClass1,SuperClass2,...)

    class Fruit:
        def info(self):
            print('我是一个水果,重%s克'%self.weight)
    
    class Food:
        def taste(self):
            print('我是能被吃的食物')
    
    #定义一个apple类继承Fruit和Food类
    class Apple(Fruit,Food):
        pass
    
    a=Apple()
    a.weight=5.6
    a.info()
    a.taste()

    运行结果

    我是一个水果,重5.6克
    我是能被吃的食物

     

    上面程序定义了两个父类,Fruit和Food,Apple可以访问父类的方法

    多继承中如果父类的方法有相同的,则最前面的那个类的方法有效(继承父类括号中的顺序,不是定义类的顺序,上面程序红色的地方)。python会从父类中搜寻方法,一旦找到就不会继续找下去。

    重写父类的方法

    class Bird:
        def fly(self):
            print('我在天上自由飞翔')
    
    class Tuoniao:
        def fly(self):
            print('我在地上自由行走')

    Bird.fly(self) #但是可以继续调用父类的重写方法
    tuo=Tuoniao() tuo.fly()

    结果:
    我在地上自由行走
    我在天上自由飞翔


    使用super函数调用父类的构造方法

    class Employee:
        def __init__(self,salary):
            self.salary=salary
        def work(self):
            print('员工的工资是%s'%self.salary)
    
    class Customer:
        def __init__(self,favorite,address):
            self.favorite=favorite
            self.address=address
        def info(self):
            print('我是一个顾客,我的爱好是:%s,地址是%s'%(self.favorite,self.address))
    
    class Manager(Employee,Customer):
        pass
    m=Manager(2500)
    m.work()
    m.info()#报错

    结果

    员工的工资是2500
    Traceback (most recent call last):
    File "F:/study/类/类的继承3.py", line 18, in <module>
    m.info()#报错
    File "F:/study/类/类的继承3.py", line 12, in info
    print('我是一个顾客,我的爱好是:%s,地址是%s'%(self.favorite,self.address))
    AttributeError: 'Manager' object has no attribute 'favorite'

     

    Manager 会优先使用Employee类的构造方法,因为它排在前面,只会有salary。

    class Employee:
        def __init__(self,salary):
            self.salary=salary
        def work(self):
            print('员工的工资是%s'%self.salary)
    
    class Customer:
        def __init__(self,favorite,address):
            self.favorite=favorite
            self.address=address
        def info(self):
            print('我是一个顾客,我的爱好是:%s,地址是%s'%(self.favorite,self.address))
    
    class Manager(Employee,Customer):
        def __init__(self,salary,favorite,address):
            super().__init__(salary)
            #super(Manager,self).__init__(salary)# 效果和上面一样
            Customer.__init__(self,favorite,address)
    m=Manager(2500,'洗澡','上海')
    m.work()
    m.info()
    
    
    结果
    员工的工资是2500
    我是一个顾客,我的爱好是:洗澡,地址是上海
  • 相关阅读:
    QML Image Element
    QML基本可视化元素--Text
    联想笔记本电脑的F1至F12键盘问题。怎么设置才能不按FN就使用F1
    Qt Creator 黑色主题配置
    虚拟机配置
    虚拟机下安装ubuntu后root密码设置
    联想(Lenovo)小新310经典版进bios方法
    带有对话框的父窗口
    添加菜单的窗口
    添加组件的窗口
  • 原文地址:https://www.cnblogs.com/inuyashalove/p/12834521.html
Copyright © 2011-2022 走看看