Object-Oriented Programming (OOP) is a programming paradigm. It solves common issues that happen in other paradigms. In this article we are going to see how to implement and use python classes and objects, with examples.
In this article, I’ll introduce you to two of the main important concepts in OOP: classes and objects.
I’ll start by defining a problem we have to solve because that is the main aim of programming, it is a tool that helps us to solve problems.
After that, I’ll write the solution in python and finally, I’ll explain some concepts that will help you to understand better.
Problem description
Company “AutoCars” has a car rental service. The manager of the company is asking you to create software that helps him to improve the business.
The company keeps a record of all the cars and the customers that at least one time rented a car with them.
For the cars, the business keeps in a record of the year model, make, type of the car (sedan, SUV, 4×4), price per day and if the car uses petrol or diesel.
For the customers, the company keeps the record of the name, id and preferred payment method (cash, ETF, card).
Your task is to design and implement a software in python that helps the manager to keep track of the cars and the customers.
In the next articles, we will add the extra needs of the manager that you will have to implement using Python.
Steps to solve the problem
As a guide to solve this problem, you will follow these steps:
- Identify all the classes from the problem description.
- Implement the classes using Python. Sometimes you cannot choose what programming language to use. In that case, the client will specify it as a requirement. But here I will use Python.
- Create a program that will use the implemented classes. For simplicity, we will use in this text-only console applications. Different programming languages deal differently with user interfaces, so we will only use console-based applications in the examples covered in this series of posts.
- Test the program created.
Python Classes
The main important concept in OOP is the concept of class, it is not the concept of object as many people think. That is the reason why any solution design starts with classes and not with objects.
Your task now is to identify classes from the problem description.
The names of the classes present in the problem description are:
- CompanyAutoCars
- Car
- Customer
But what is a class?
As an informal way of identifying classes, we can say a class is a concept that represents several objects (of the same type) from the real world. For instance, in our neighbourhood we can find several houses, the houses are objects from the real world, so the word house is a concept that represents all the houses in our neighbourhood.
In the case of the problem that we are trying to solve, we have the company, cars and customers. The concept:
- “CompanyAutoCars” represents the company we want to help by creating the software.
- “Car” represents all the cars that the company have.
- “Customer” represent all the people that rented a car to the company.
Can you see the pattern here?
Attributes in Python
There is a second element that a class must have: the attributes. Attributes are values that describe the objects (from the real world). For instance, in our previous example of the houses, a house can have a physical address, a colour, a size (usually expressed in square meters), a price (according to a certain valuation). Those characteristics are the attributes of that class.
In the problem we are solving, what are the characteristics of cars (according to the description of the manager)?
The characteristics are:
- year model
- make
- type of car
- price per day
- diesel or petrol
Last but not least, classes have methods. Methods are the actions we can execute on the objects that the class represents.
For instance, if we want to know the make of a car, we have to create a method in the class Car.
Let’s see the code in Python for the class Car.
It is not compulsory, but it is desirable to follow style guides for coding. The guide for python is here. See below the conventions I gonna use in the next code sample.
“Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
Use one leading underscore only for non-public methods and instance variables.”
Example
class Car:
def __init__(self, year_model, make, type, price_per_day, fuel):
self._year_model = year_model
self._make = make
self._type = type
self._price_per_day = price_per_day
self._fuel = fuel
Ohh!!?? wait, what the heck is this? What is the meaning of def __init__. Let me explain everything in the previous python code.
The keyword “class” is the way we tell python we are gonna define a class. What comes after that is the name of the class (we already identified the names) and the semicolon (:) means we are gonna start a new block of code. In this case, the block that comes after is the class implementation.
Next keyword is “def”. The first thing to notice here is the indentation (the blank spaces in front of def). Python defines blocks of code according to the indentation; other languages commonly use brackets to identify blocks of code (“{}”). If the indentation is not right your program will give errors.
Methods and constructors in Python
The second thing we see in that line of code is “__init__(…)”. In Python, this is called a class constructor. The objective of the constructor is to assign initial values to the attributes. Let’s say you are creating a car, then you have to assign certain initial values to the attributes of the car. It does not make sense to have a car without a year model, or a make, or type.
What you see between parenthesis on the same line, it is called parameters. Parameters are extra information that methods need to do what they suppose to do. In our case, the method “__init__” (a special method called constructor) have to assign initial values to the attributes, so what values to assign? We don’t know, they are not fixed values, so we use parameters.
The keyword “self” is always the first parameter. Is the way that we get access to the class attributes in Python.
So, what are the attributes of the class car? The attributes of the class are the ones that start with an underscore (_) and are after the keyword “self”. The attributes are _year_model, _make, _type, _pricer_per_day and _fuel. Notice that when we what to have access to the class attributes we have to use the keyword “self”, followed by a “.” and then the name of the attribute.
The underscore (_) before the name of the attribute means that the attribute is not public. Class attributes have three visibility levels: public, protected and private. For now, just assume all the attributes are not public and we will use in Python an underscore (_) as per the python code style guide.
Notice that the first line after the constructor definition (“self._year_model …”) starts with a new indentation level, four blank spaces from the level of the constructor definition. This means the line of code is within the constructor.
Uff!!, I hope you are not already bored because of this explanation. I’m avoiding a lot of theory and concepts, I’m trying to explain the basis in a way that you can understand how to do it on your own later.
Example
So, let’s see how the other classes look like.
class Customer:
def __init__(self, name, id, prefered_payment_method):
self._name = name
self._id = id
self._prefered_payment_method = prefered_payment_method
class CompanyAutoCars:
def __init__(self):
self._customers = []
self._cars = []
def add_customer(self, customer):
self._customers.append(customer)
def add_car(self, car):
self._cars.append(car)
def get_number_of_cars(self):
return len(self._cars)
def get_number_of_customers(self):
return len(self._customers)
Notice again how the indentation specifies what block of code belongs to what class or method (so far, we only have constructors).
There is something new in the last class (“[]”). That symbol specifies that the attribute “_customers” will have several values. In other words, it is a list. Remember the company have several customers and cars. We have to use a list to store several values. In python, we do that as specified in the constructor of the class “CompanyAutoCars” (attribute = []).
Also, we have to extra methods. We will use the first one to add a new customer to the company, and the second one to add a new customer.
In Python, when we define an attribute as a list (“[]”), we get extra benefits. We can use methods implemented for lists. On example is the method “append”, it will add the value passed as a parameter to the list.
Let’s take a closer look at the example.
self._customers.append(customer)
The attribute is “_costumer”, which is a list. Initially, we decided that the list will be empty. If you just create a company you still don’t have customers. But we need to find a way to add new customers otherwise the company will go bankrupt. So we use the method “append” that python lists provide, and we specify what we want to append. In our case, we want to append a customer.
We will use the last two methods to find out if the code is working well. The explanation of what they do is easy.
They just return the length of the corresponding list, i.e. the list of customers and the list of cars.
Some methods return a value, like the last two. In that case, we want to know the result, the length of the list. Some does not return a value, like a method “add_car”. In this case, we just want the car added, not a specific value.
Python objects
After implementing the classes, we have to use them. The way we use them is through objects. There is a specific type of class that can be used without objects, but let’s start with the basics first: objects.
An object in OOP is an instance of a class. An instance means that the class will have specific values for the attributes. As you saw in the class implementation, we defined parameters in the constructor (not specific values). To create objects, we have to specify specific values.
Let’s create an object from the customer class. In other words, let’s create a customer.
customer1 = Customer("John Doe", "1234", "ETF")
In this example, “customer1” is the name of the object. We create a new object by using the class name and specifying a value for each parameter in the constructor of the specific class (ignoring the parameter “self”). The parameters must be specified in the same order they were defined in the constructor.
class Customer:
def __init__(self, name, id, prefered_payment_method):
...
Our new customer has the following attributes: _name = “John Doe”, _id = “1234”, _prefered_payment_method = “ETF”
Create the program (console application)
Check the code below for the console application.
if __name__ == '__main__':
#create the objects
customer1 = Customer("John Doe", "1234", "ETF")
customer2 = Customer("Jane Doe", "1347", "Cash")
car1 = Car("2021", "BMW", "Sedan", 200, "Petrol")
autocars = CompanyAutoCars()
#add a new car to the company
autocars.add_car(car1)
# add two customers to the company
autocars.add_customer(customer1)
autocars.add_customer(customer2)
# print the number of customers and cars to test if they were added
print("Number of cars in the company: ", autocars.get_number_of_cars())
print("Number of customers in the company: ", autocars.get_number_of_customers())
Python files can be used in two ways. The first one as a console application. The second one as a library to use defined class or functions (functions are methods that do not belong to a class).
The first line of the code above specifies that the block of code after the keyword “if” will only be executed if the file is executed as a console application.
If the file is included in another file, so you can use the classes implemented there, the code after the “if” won’t be executed.
In Python, we use “#” to write comments in the code. Comments are an explanation of what the code does and are not considered when we execute the code. As you can see the comments make it easier to understand the code.
First, we create objects. Second, we add a car and two customers to the company. Lastly, we print how many customers and cars are in the company. By doing that, we are testing that the methods to add customers and cars works well.
Summary
To summarise this long article (hopefully not too boring):
- Class is the main concept in OOP.
- An object is an instance of a class.
- Every class have a constructor.
- Constructors are used to initialising objects.
- A Class have methods that are used through objects to act on the object.
- We can test our code by creating console applications.
- In Python, indentation is one of the main things to learn. If the code is not properly indented it won’t work.
- In real-life situations, we have to identify classes from a description that someone will give us.
What now?
Try to reproduce the code in this article in your computer and let me know in the comments the results. You can use pyCharm to write your Python code. It has a free version.
Leave any question about this topic below in the comment section. Even if you don’t have any question, let me know what you think about the post.
I’ll soon have more posts and will explain more about OOP in Python with examples.
Want to try something on your own? Find below a problem to solve.
The coffee shop “AwesomeCoffee” sell the best coffee in your neighbourhood. The manager of the shop is asking you to create a software that helps her to improve the business. The company keeps a record of the customers that buys coffee. For the customers the company keeps knows the name and email address. To satisfy all the customers, the shop sells coffee in several sizes. The shop knows the size of the coffee cup (ml) and the price. From the above description: Identify and implement the classes. Create a console application that shows your classes are well implemented.
Visit my blog for more content.
Other links related to programming:
H@appy coding!!!
This is nice and educative for me. Thank you
Happy to help. You can also suggest topics using the contact link from the menu.
I appreciate you for this, I would like to learn more still on your blog
Great!! I suggest you to subscribe to the newsletter so you don’t miss any new post. It is free. See the form on the right side. You can also make a comment asking for more detailed explanation on the topic. You can do it here or using the contact page (using menu on top).
H@appy coding!!