九、类4(2022-04-17)

3.5模拟实物

模拟较复杂的事物时,会有不同的需求。如果需要返回一辆燃油摩托的续航里程,可以在get_range的形参中加入motor_model参数,并设定语句返回其续航里程。

class Battery:
    def __init__(self, battery_size=90, motor_model='electric'):
        self.battery_size = battery_size
        self.motor_model = motor_model

    def describe_battery(self):
        print(f"The Motor has a {self.battery_size}-kwh battery.")

    def get_range(self, battery_size, motor_model):
        """打印一条消息,指出点评的续航里程"""
        if battery_size > 0 and motor_model == 'electric':  #注意条件语句,用self.battery_size会导致传参失败,会一直传入默认参数 battery_size = 90,同样self.motor_model 则会一直传入motor_model='electric',造成条件判定问题
            range = battery_size * 0.75
            print(f"This motor can go about {range} miles on a full charge")
        if battery_size == 0 and motor_model != 'electric':
            range = int(input("plesas input the tank capacity.")) * 10
            print(f"This motor can go about {range} miles on a full tank.")


class ElectricMotor3(Motor):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()


my_yadi = ElectricMotor3('yadi', 'm6', 2019)
print(f"My motor bike is {my_yadi.get_descriptive_name()}")
my_yadi.battery.describe_battery()
my_yadi.battery.get_range(battery_size=100, motor_model='electric')
my_yadi.battery.get_range(battery_size=0, motor_model='feul')

My motor bike is 2019 Yadi M6
The Motor has a 90-kwh battery.
This motor can go about 75.0 miles on a full charge
plesas input the tank capacity: 90
This motor can go about 900 miles on a full tank.

你可能感兴趣的:(九、类4(2022-04-17))