19.8k views
0 votes
Implement a class Car with the following properties. A car has a certain fuel efficiency (measured in miles/gallon or liters/kmâpick one) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor, and the initial fuel level is 0. Supply a function drive that simulates driving the car for a certain distance, reducing the fuel level in the gas tank, and functions get_gas, to return the current fuel level, and add_gas, to tank up. Sample usage:Car my_beemer(29); // 29 miles per gallonmy_beemer.add_gas(20); // Tank 20 gallonsmy_beemer.drive(100); // Drive 100 milescout << my_beemer.get_gas() << "\\"; // Print fuel remaining

User Inikulin
by
6.4k points

1 Answer

9 votes

Answer:

class Car(object):

fuel = 0

def __init__(self, mpg):

self.mpg = mpg

def drive(self, mile):

if self.fuel * self.mpg >= mile:

self.fuel -= mile / self.mpg

else:

print(f"get gas for your {self}")

print(f"Fuel remaining: {self.fuel}")

#classmethod

def get_gas(cls):

cls.fuel += 50

#classmethod

def add_gas(cls, gallon):

if cls.fuel + gallon > 50:

cls.fuel += 10

else:

cls.fuel += gallon

gulf = Car(20)

gulf.get_gas()

gulf.drive(200)

Step-by-step explanation:

The Car class is defined in Python. Its drive method simulates the driving of a car with fuel that reduces by the miles covered, with efficiency in miles per gallon. The get_gas and add_gas methods fill and top up the car tank respectively.

User Rajni
by
5.7k points