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

    class Car():
        '''一次模拟汽车的简单尝试'''
    
        def __init__(self,make,model,year):
            '''初始化描述汽车的属性:制造商、型号、生产年份'''
    
            self.make = make
            self.model = model
            self.year = year
            self.odometer_reading = 24              #里程表读数
    
        def update_odometer(self,mileage):      #修改属性值
            '''将里程表读数设置为指定的值'''
    
            self.odometer_reading += mileage
    
    
        def get_descriptive_name(self):
            '''返回整洁的描述信息'''
    
            long_name = str(self.year) + '   ' + self.make + '   ' + self.model
    
            return  long_name.title()
    
        def read_odometer(self):
            '''打印一条指出汽车里程的信息'''
            print('这辆车的汽车里程是:  ' + str(self.odometer_reading))
    
    
    #--------------------------------------------------------------------
    
    class ElectricCar(Car):
        '''电动车的独特之处'''
    
        def __init__(self,make,model,year):
            '''初始化父类属性'''
            super().__init__(make,model,year)
    
            self.battery_size = 70            #添加一个电动车特有的属性:电瓶,以及电瓶容量
    
    
        def describe_battery(self):
            '''打印一条描述电瓶容量的信息'''
    
            print('这辆电动车有: ' + str(self.battery_size) + ' 的电瓶容量')
    
    
    
    my_tesla = ElectricCar('特斯拉','model  s ',2016)
    
    print(my_tesla.get_descriptive_name())
    
    #-------------------------------------------------------
    
    my_tesla.read_odometer()
    
    my_tesla.describe_battery()
    
    #-------------------------------------------------
    
    my_tesla.battery_size = 100
    
    my_tesla.describe_battery()
    
    
    
    ===================================================================
    
    执行结果:
    
    
    2016   特斯拉   Model  S 
    
    这辆车的汽车里程是:  24
    
    这辆电动车有: 70 的电瓶容量
    
    这辆电动车有: 100 的电瓶容量
    
    
    ========================================================================
    
    
    创建子类时,父类必须包含在当前文件中,且位于子类前面。
    
    
    
    定义子类时,必须在括号内指定父类名称。
    
    
    方法_init_接收创建Car实例所需的信息。
    
    
    
    super()是一个特殊的函数,帮助python把父类和子类关联起来。
    
    
    ——让python调用ElectricCar的父类方法的_init_,让ElectricCar实例包含父类的所有属性,
    
        父类也称之为超类,super因此得名;
  • 相关阅读:
    推荐美丽的flash网页MP3音乐播放器
    android混合动画实现
    swift UI专项训练39 用Swift实现摇一摇功能
    The return type is incompatible with JspSourceDependent.getDependants():JasperException问题分析与解决方法
    【翻译自mos文章】注意: ASMB process exiting due to lack of ASM file activity
    表格对象QTableWidget相关常见方法
    python 加密解密
    python报错ordinal not in range(128)
    scp,ssh双机互信操作步骤
    PyQt多窗口调用
  • 原文地址:https://www.cnblogs.com/xiaobaibailongma/p/12061284.html
Copyright © 2011-2022 走看看