Python: Object Oriented Programming (OOP)
Python Object Oriented Programming (OOP)
1 Overview
📘 Object Oriented Programming (OOP)
In Python, Object Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
2 Object Oriented Programming (OOP)
- Organizes code like a community of interacting individuals.
- Benefits: Manageable, maintainable, reusable code.
3 Python Classes and Objects
- Classes: Blueprints (like architectural plans).
- Objects: Instances built from the blueprint (like houses).
- Use a class blueprint to create multiple objects.
- It is like building multiple houses (objects) from the same architectural plan (class).
4 Object intuiton
- Objects represent “real-life” entities.
- They have properties (attributes) and behaviors (methods / “functions”).
- Defined by the programmer.
4.1 Example 1
What abstract entities do we have in Tic-Tac-Toe?
Classes:
- Player
- Attributes: name.
- Methods: update name.
- Board
- Attributes: num. squares (3x3?).
- Methods: Display board, set piece, check legal moves.
- Game
- Attributes: board, list of players.
- Methods: play game, reset game.
Object instances built from class definitions:
- 2 players
- 1 board
- 1 game
4.2 Example 2
What abstract entities do we have in a store?
Classes:
- Product
- Attributes: quantity, description, brand.
- Methods: update stock, apply discount.
- Client
- Attributes: name, phone num., client score, order history.
- Methods: update contact info, view order history.
- Employee
- Attributes: name, phone num., bank account, salary, role.
- Methods: increase salary, update bank account.
- Order
- Attributes: products, client, total price.
- Methods: add product, remove product, process payment.
- Store
- Attributes: clients, products, employees.
- Methods: add products, remove products, add employee.
4.3 Example 3
- Python is an object-first language.
- This means we’ve been using objects all along.
- Behind the scenes, everything is an object.
- Strings are objects, integers are objects, functions are objects.
- For example, creating a string object:
4.3.1 String class:
- Attributes
- __doc__
- __class__
- …
- Methods
- lower()
- replace()
- count()
- …
- Defining a
Productclass in Python (preferably in upper camel case): - The
Productclass definition is the blueprint. - p1 and p2 are different instances of product built from the blueprint.
5 __init__()
- Automatically called when a new object is created.
- Initializes object attributes.
- Why double underscores (
__)? - What is this
self?
True
6 self
- Refers to the object instance being created.
- Used to access object attributes.
- Think of
selfas a way to refer to the object instance itself.
And the other does not change, because name is in the self:
You can also add new attributes to the self without affecting other instances:
7 Class attributes
Are shared among all object instances.
- If you change a class attribute, all instances change:
0.1
- Take care!
- If you do this, you’re creating a new attribute inside the
self. - It shadows the class attribute.
- Now the class attribute
tax_ratehas no impact onp1anymore.
0.1
Parameter names in the __init__() function can have any name, they do not necesseraly have to be named equal to the :
8 Class methods
- Functions that define actions an object can take.
selfalways has to be the first parameter, as all methods can access it.- For example,
update_stock:
9 Creating an Object
Instantiate (build) using the class blueprint.
What is happening internally?
- Memory is allocated for the new object.
__init__()method is called automatically.- Attributes set within
__init__()are initialized. - The new object (with its initialized attributes) is returned and assigned to the variable (
cakein this case).
When a method changes an attribute in the self, it changes everywhere:
Note that…
- Notice that we don’t write
selfwhen calling an object’s methods. - However, every instance method must include
selfas its first parameter. - Python automatically passes the instance (
self) behind the scenes when the method is called.
10 More methods
class Product:
def __init__(self, name, unit_price, quantity=1):
self.name = name
self.unit_price = unit_price
self.quantity = quantity
def update_stock(self, amount):
self.quantity += amount
print(f'New quantity: {self.quantity}')
def get_discounted_price(self, discount):
return self.unit_price - self.unit_price * discount
def describe(self):
print(self.name)
print(f'Quantity: {self.quantity}')
print(f'Unit price: {self.unit_price}€')Quantity: 10
Unit price: 1.79€
11 Multiple instances
- We can create multiple instances of the same object type.
- They remain independent.
- Changing one does not (normally) influence the other.
- For example:
- milk1 and milk2.
- Multiple pandas DataFrames.
- Multiple objects of the same class.
Quantity: 1
Unit price: 0.1€
Quantity: 20
Unit price: 3.95€
12 Dunder (double underscore) methods
- These are commonly referred to as “dunder” (short for “double underscore”).
- Methods surrounded by double underscores are special methods in Python.
- They have specific purposes and are used to override default behaviors in Python.
- For example,
__init__()is called automatically when an object is instantiated. - Other examples:
__str__()or__add__()
13 str
- Returns a human-readable string representation of the object.
- By default, an object is not printable per se:
After defining __str_() we can print it as we like:
class Product:
def __init__(self, name, unit_price, quantity=1):
self.name = name
self.quantity = quantity
self.unit_price = unit_price
def update_stock(self, amount):
self.quantity += amount
print(f'New quantity: {self.quantity}')
def get_discounted_price(self, discount):
return self.unit_price - self.unit_price * discount
def describe(self):
print(self.name)
print(f'Quantity: {self.quantity}')
print(f'Unit price: {self.unit_price}€')
def __str__(self):
# Returns product's name and quantity
return f'{self.name}: {self.quantity}'14 Operator Overloading
- Using standard operators (like
+,-,*) with custom logic for objects. - Intuitive operations for custom objects.
- By default, we cannot add object instances:
After defining __add_() we can add them:
class Product:
(...)
def __str__(self):
# Returns product's name and quantity
return f"{self.name}: {self.quantity}"
def __add__(self, other):
# Behavior when adding Products
same_name = self.name == other.name
same_price = self.unit_price == other.unit_price
if same_name and same_price:
total = self.quantity + other.quantity
return Product(self.name, self.unit_price, total)
else:
raise Exception("Cannot add these two products.")15 Managing Invoices
Simple class Product (see example below)
16 Exercises
16.1 Circle and Rectangle
Create a Circle class that represents a circle with a specified radius. This class should have methods to calculate the area and circumference of the circle and return it. The area is calculated using the formula π * radius², and the circumference is calculated using the formula 2 * π * radius.
Additionally, create a Rectangle class that represents a rectangle defined by its length and width. This class should include methods to calculate the area and perimeter of the rectangle and return their values. The area is calculated using the formula length * width, and the perimeter is calculated using the formula 2 * (length + width).
16.2 Shopping Cart
Design a simple shopping cart system that includes a Product class and a ShoppingCart class. The Product class should have attributes for product_id, product_name, and product_price, along with a method display_product_info() to show the product details. The ShoppingCart class should maintain a list of products and provide methods to add products, remove products by their ID, and calculate the total cost of the items in the cart.
16.3 Flight Booking System
Create two classes: Passenger and Flight. The Passenger class should store details such as name, passport_number. The Flight class should contain information like flight_number, origin, destination, and a list of passengers (which are instances of the Passenger class).
Additionally, implement an external function book_flight(flight, passenger) (not part of any of the previous classes) that adds a passenger to a flight. This function should ensure that a passenger cannot be booked more than once, which is determined by checking their passport_number.
16.4 Sports League
Implement a simple system for managing a sports league, where each team has several players with individual performance scores.
- Class
Player: should include attributes such asname,position, andperformance_score. - Class
Team: should include attributes liketeam_nameand a list ofPlayerobjects. - External function
best_player(team): this function must not be part of any class. It should receive a Team object as parameter, iterate through its list of players, and return the Player with the highest performance_score. Check the example code to see how to implement your classes and the external function correctly.
16.5 School Management
Implement a simple system to manage a school, keeping track of students and the courses they are enrolled in.
- Class
Course: should represent a subject (e.g., Mathematics, Science) and include attributes such ascourse_nameandcourse_code. - Class
Student: should include attributes likestudent_id,name, andenrolled_courses(a list ofCourseobjects). - External function
is_enrolled(student, course_code): this function must not be part of any class. It should receive aStudentobject and acourse_code, and returnTrueif the student is enrolled in that course, orFalseotherwise.
16.6 Robot Dance Party
Hosting a Robot Dance Party is needed to design two classes that work together to simulate the event:
- Class
RobotDancer: represents a single robot dancer. Each robot should have:robot_id: a unique identifier for the robot.name: the robot’s name.dance_move: the name of its dance move (e.g., “Moonwalk”, “Robot Wave”).- The class should include a method
dance()that prints a message like: - R2D2 is doing the Moonwalk!
- Class
DanceFloor: represents the dance floor where robots perform. It should:- Store a list of
RobotDancerobjects. - Include a method
add_robot(robot)to add a new robot to the floor. - Include a method
display_robots()that lists the name of the robots currently on the dance floor. Print a special message in case there are no robots on the dance floor. - Include a method
start_dancing()that makes all robots perform their dance moves by calling each robot’sdance()method. Print a special message in case there are no robots on the dance floor.
- Store a list of
16.7 Inventory Management System
Design an inventory management system for a local store called MiniMart. The goal is to help the store track products, manage stock, and generate simple sales reports. In this system, the MiniMart class is responsible for keeping track of how many units of each product are in stock. Each product itself only describes what it is and how much it costs.
- Class
Product: represents an item that can be sold by the store. Each product should have:product_id: a unique identifier.name: the product’s name (e.g., “Apple”).price: the price per unit.
This class does not manage stock quantities — the store does.
- Class
MiniMart: represents the store and manages:- The available products and their current quantities. The store keeps track of available products and their quantities using a dictionary. Each key is a product ID, and its value is another dictionary containing the product object under the key “product” and the current stock under the key “quantity”
- Adding new products to the store inventory. Consider a product might already be in the store, so you should not be able to add it.
- Selling products (reducing stock and increasing total revenue). When attempting to sell a product, if the requested quantity exceeds the available stock, the sale should be blocked — the stock should remain unchanged, and an error message should be displayed indicating insufficient stock. Also, display an error message if the product to be sold is not in the store.
- Restocking products (increasing stock).
- Generating sales reports that display total revenue and list products that are low in stock (less than 5 units).
