Python: Object Oriented Programming (OOP)
Python Object Oriented Programming (OOP)
python
oop
objects
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 Intuition
- Objects represent “real-life” entities.
- They have properties (attributes) and behaviors (methods/“functions”).
- Defined by the programmer.
5 Example 1: Tic-Tac-Toe Entities
5.1 Classes:
- Player Attributes: name Methods: update name
- Board Attributes: number of squares (e.g., 3x3) Methods: Display board, set piece, check legal moves
- Game Attributes: board, list of players Methods: play game, reset game
5.2 Object Instances:
- 2 players
- 1 board
- 1 game
6 Example 2: Store Entities
6.1 Classes:
- Product Attributes: quantity, description, brand Methods: update stock, apply discount
- Client Attributes: name, phone number, client score, order history Methods: update contact info, view order history
- Employee Attributes: name, phone number, bank account, salary, role Methods: increase salary, update bank account
- Order Attributes: products, client, total price Methods: add product, remove product, process payment
7 Example 3: Python is Object-First
- Everything in Python is an object.
- Strings, integers, functions are objects.
- For example, creating a string object:
8 String Class Example
- Attributes:
__doc__
,__class__
, … - Methods:
lower()
,replace()
,count()
, …
9 Defining a Class in Python
- Classes usually use UpperCamelCase names.
- The class definition is the blueprint.
- Instances are objects built from the blueprint.
Example:
10 __init__
Method
- Automatically called when a new object is created.
- Initializes object attributes.
self
refers to the instance being created.
Example:
11 self
Keyword
- Refers to the object instance.
- Used to access object attributes.
- Think of
self
as a way for methods to refer to the object itself.
12 Changing Object Attributes
Example:
- Changing
p1.name
does not affectp2.name
.
You can add new attributes to objects dynamically:
13 Class Attributes
- Shared across all instances.
Example:
- If you change a class attribute, all instances reflect the change:
- Beware: Assigning to an instance attribute with the same name shadows the class attribute:
14 Class Methods
- Define actions the object can take.
self
must always be the first parameter.
Example:
Creating an object:
When calling a method, you do not pass self
explicitly; Python passes it behind the scenes.
15 More Methods Example
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}€')
cake = Product('Cake', unit_price=1.79, quantity=10)
cake.describe()
16 Dunder (Double Underscore) Methods
- Special methods surrounded by double underscores.
- Have specific purposes, like overriding Python behaviors.
__init__
called automatically on object creation.- Examples:
__str__
,__add__
.
Example:
Usage:
17 Operator Overloading
- Enables use of operators (+, -, *) with custom behaviors for objects.
- By default, adding two custom objects results in a TypeError.
Example of enabling +
operator:
class Product:
# Other methods...
def __add__(self, other):
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.")
Example of use:
pizza1 = Product('Pizza - Tarradellas', unit_price=3.95, quantity=8)
pizza2 = Product('Pizza - Tarradellas', unit_price=3.95, quantity=3)
pizza3 = Product('Pizza - Buittoni', unit_price=4.10, quantity=10)
new_pizza = pizza1 + pizza2
print(new_pizza) # Pizza - Tarradellas: 11
new_pizza = pizza1 + pizza3
# Exception raised: Cannot add these two products.
18 Complex Example: Library System
Classes for managing a book library:
class Book:
def __init__(self, tit, auth):
self.title = tit
self.author = auth
self.availability = True
def borrow(self):
if self.availability:
self.availability = False
print(f"{self.title} has been borrowed.")
else:
print(f"{self.title} is not available.")
def return_book(self):
self.availability = True
print(f"{self.title} has been returned.")
def __str__(self):
return f"{self.title} - {self.author}"
class Library:
def __init__(self, name, loc):
self.books = []
self.name = name
self.location = loc
def add_book(self, book):
self.books.append(book)
return f"{book.title} added to the library."
def get_book(self, title):
for book in self.books:
if book.title == title:
if book.availability:
return book
else:
print(f"{title} is currently borrowed.")
return None
print(f"{title} not found in the library.")
return None
Example usage:
pilarin_bayes = Library("Pilarin Bayés", "Vic")
joan_miro = Library("Joan Miró", "Barcelona")
hp1 = Book("Harry Potter 1", "J.K. Rowling")
hp2 = Book("Harry Potter 2", "J.K. Rowling")
hp3 = Book("Harry Potter 3", "J.K. Rowling")
hp4 = Book("Harry Potter 4", "J.K. Rowling")
pilarin_bayes.add_book(hp1)
pilarin_bayes.add_book(hp2)
joan_miro.add_book(hp2)
joan_miro.add_book(hp3)
joan_miro.add_book(hp4)
my_hp1 = joan_miro.get_book("Harry Potter 1")
print(my_hp1) # Harry Potter 1 not found in the library. None
my_hp1 = pilarin_bayes.get_book("Harry Potter 1")
print(my_hp1) # Harry Potter 1 - J.K. Rowling
my_hp1.borrow() # Harry Potter 1 has been borrowed.
my_hp1 = pilarin_bayes.get_book("Harry Potter 1")
print(my_hp1) # Harry Potter 1 is currently borrowed. None