Python – Abstract Methods and Abstract Class – Live Coding Video

Abstract class and abstract methods are one of the pillars of Object Oriented Programming. In Python, an abstract class is a class, inheriting from Abstract Base Classes (ABC) library. And an abstract method is a method of this class, which cannot be initialized and has a decorator @abstractmethod.

About 1 year ago I wrote an article about refactoring a C# problem with abstract methods. Today, I have decided to solve a similar problem with live coding and with Python. So, the problem, as written by SoftUni, looks like this:

  1. Create an abstract class called Vehicle that should have abstract methods drive and refuel.
  2. Create 2 vehicles that inherit the Vehicle class (a Car and a Truck) and simulates driving and refueling them.
  3. Car and Truck both have fuel_quantity, fuel_consumption in liters per km and can be driven a given distance: drive(distance) and refueled with a given amount of fuel: refuel(fuel). It is summer, so both vehicles use air conditioners and their fuel consumption per km when driving is increased by 0.9 liters for the car and with 1.6 liters for the truck.
  4. Also, the Truck has a tiny hole in its tank and when it’s refueled it keeps only 95% of the given fuel. The car has no problems and adds all the given fuel to its tank. If a vehicle cannot travel the given distance, its fuel does not change.

And the tests that should work with it are these ones:

car = Car(20, 5)
car.drive(3)
print(car.fuel_quantity)
car.refuel(10)
print(car.fuel_quantity)
2.299999999999997
12.299999999999997
truck = Truck(100, 15)
truck.drive(5)
print(truck.fuel_quantity)
truck.refuel(50)
print(truck.fuel_quantity)
17.0
64.5

Yup. The video with the live coding is here:

Enjoy it! 🙂

Tagged with: , , ,