From Procedural Python to Object Orientation

A look at how to refurbish Python code to use Classes, Attributes, Encapsulation, Inheritance, and Polymorphism

Sami Islam

--

Photo by ian dooley on Unsplash

In this article, I am going to go through some procedural code in Python and update that to Object-Oriented code using Classes, Attributes, Encapsulation, Inheritance, and Polymorphism.

I use Visual Studio Code with the pipenv Python package manager, Python v3.8.2, and the compile-time static type checker mypy. You can find more about this setup in my article:

Let’s get started!

Procedural code

There are two hypothetical shops: The Computer Shop and The Rebuy Shop. The following code shows how they are being used:

The procedural code for the shops using a computer
The procedural code for the shops using a computer

Both the Computer Shop and the Rebuy Shop offer the following functionality:

  • buy a computer
  • update its price
  • sell a computer
  • print details about a computer

The Rebuy Shop can additionally:

  • refurbish a computer

The output of running the code above:

The output of running the procedural code for the shops using a computer
The output of running the procedural code for the shops using a computer

Now let’s look at the shops:

The procedural code for the Computer shop
The procedural code for the Computer shop

The Computer Shop has the functionality: buy, update_price, sell, and print_item. It has an inventory to store all the computers it buys. The Rebuy Shop looks almost exactly the same with the addition of refurbish.

--

--