Python编写汽车类

Python编写汽车类

编写程序并测试,有一个汽车类 Vehicle,类中的私有数据成员为车轮个数
wheels 和车重 weight;小车类 Car 是汽车类 vehicle 派生类,其中包含载客人数
passenger_load,默认 4 人;卡车类 Truck 是汽车类 vehicle 派生类,其中包含载客
人数 passenger_load 和载重量 payload。
代码如下:

class Vehicle(object):
    def __init__(self,wheels,weight):
        self.setWheels(wheels)
        self.setWeight(weight)
    def setWheels(self,wheels):
        self.__wheels=wheels
    def setWeight(self,weight):
        self.__weight=weight
    def getWeight(self):
        return self.__weight
    def getWheels(self):
        return self.__wheels
    def show(self):
        print("轮胎数为:"+str(self.getWheels())+","+"重量为:"+str(self.getWeight()))
class Car(Vehicle):
    def __init__(self,wheels,weight,passenger_load=4):
        super(Car,self).__init__(wheels,weight)
        Vehicle.__init__(self,wheels,weight)
        self.setPassenger(passenger_load)
    def setPassenger(self,passenger_load):
        self.__passenger_load=passenger_load
    def getPassenger(self):
        return self.__passenger_load
    def show(self):
        super(Car,self).show()
        print("载客量为:"+str(self.getPassenger()))
class Truck(Vehicle):
    def __init__(self,wheels,weight,passenger_load,payload):
        super(Truck,self).__init__(wheels,weight)
        Vehicle.__init__(self,wheels,weight)
        self.setPassenger(passenger_load)
        self.setPayload(payload)
    def setPassenger(self,passenger_load):
        self.__passenger_load=passenger_load
    def setPayload(self,payload):
        self.__payload=payload
    def getPayload(self):
        return self.__payload
    def getPassenger(self):
        return self.__passenger_load
    def show(self):
        super(Truck,self).show()
        print("载客量为:"+str(self.getPassenger())+","+"载重量为:"+str(self.getPayload()))
if __name__=='__main__':
    vehicle=Vehicle(10,150)
    vehicle.show()
    car=Car(5,50)
    car.show()
    truck=Truck(12,200,12,200)
    truck.show()

运行结果如下:
Python编写汽车类_第1张图片

你可能感兴趣的:(python,python)