Python入门到实践(9)-类的继承

来源:互联网 发布:gis软件开发工程师 编辑:程序博客网 时间:2024/04/30 07:09
# -*- coding: utf-8 -*-"""Created on Mon Dec 04 21:22:37 2017@author: Echo"""#类的继承class Car():#父类    """一次模拟汽车的尝试"""        def __init__(self,make,model,year):        self.make=make        self.model=model        self.year=year        self.odometer_reading=0 #制定属性的默认值    def get_descriptive_name(self):        long_name=str(self.year)+' '+self.make+' '+self.model        return long_name.title()        def read_odmeter(self):        print("This car has "+str(self.odometer_reading)+"miles on it!")        def update_odmeter(self,mileage):#防止私自修改历程数属性        if mileage>=self.odometer_reading:            self.odometer_reading-mileage        else:            print("请输入大于当前里程的数值")    def fill_gas_tank():        print("This Car dosen't have gas")class ElectriCar(Car): #子类    def __init__(self,make,model,year):        Car.__init__(self,make,model,year)        self.battery=70#添加子类属性         def discribe_barrery(self):#添加子类方法        print("This car has "+str(self.battery)+"- KWh battery!")        def fill_gas_tank():#重写父类方法        print("This Car dosen't need a gas tank!")my_electricar=ElectriCar('tesla','A3',2015)print(my_electricar.get_descriptive_name())class Battery():#电池类    def __init__(self,battery_size=70):        self.battery_size=battery_size        def describe_battery():        print("This car has "+str(self.battery)+"- KWh battery!")class ElectriCarNew(Car): #子类    def __init__(self,make,model,year):        Car.__init__(self,make,model,year)        self.battery=Battery()#使用实例作为其他类的属性


 
阅读全文
0 0
原创粉丝点击