Skip to main content

3.2 - Classes & Objects

3.2.1 - Introduction

Classes and objects are the cornerstones of object-oriented programming (OOP) in Python. They allow you to create reusable and organized code structures that model real-world entities.


3.2.2 - What is a Class?

3.2.2.1 - Definition

A class is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from it will have. Attributes are variables that store data, while methods are functions that perform actions.

3.2.2.2 - Why Use Classes?

  1. Reusability: Once a class is defined, you can create multiple objects from it without redefining the code.
  2. Organization: Classes help in logically grouping related data and functions.
  3. Modularity: Classes make it easier to split up and manage large codebases.

3.2.3 - Creating a Class

To define a class in Python, you use the class keyword followed by the class name and a colon. The class body contains attributes and methods.

class MyClass:
# attributes and methods here

Here's a simple example of a class that models a dog.

class Dog:
species = "Canis lupus familiaris" # Class attribute

def bark(self): # Method
print("Woof, woof!")

3.2.4 - Creating an Object

3.2.4.1 - Instantiation

Creating an object from a class is called instantiation. You can instantiate an object using the class name followed by parentheses.

my_dog = Dog()

3.2.4.2 - Accessing Attributes and Methods

You can access the attributes and methods of an object using the dot (.) notation.

print(my_dog.species)  # Output: Canis lupus familiaris
my_dog.bark() # Output: Woof, woof!

3.2.5 - Attributes and Methods

3.2.5.1 - Instance Attributes

These are attributes that belong to individual objects and can have different values for different objects.

class Dog:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute

3.2.5.2 - Class Methods

Methods are functions defined within a class. They usually manipulate the attributes of the object or perform some computation.

class Dog:
def bark(self):
print("Woof, woof!")

3.2.6 - Class Constructors and Destructors

3.2.6.1 - Constructors

  • Constructors are special methods automatically invoked when an object is created.
  • In Python, constructors are defined using the __init__ method.
  • They are used to initialize the object’s state.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

3.2.6.2 - Destructors

  • Destructors are called when an object is about to be destroyed.
  • In Python, destructors are defined using the __del__ method.
  • They are less commonly used but can be helpful for cleaning up resources, like closing file connections.
class FileHandler:
def __init__(self, filename):
self.file = open(filename, 'r')

def __del__(self):
self.file.close()
print("File closed.")

3.2.6.3 - When to Use Constructors and Destructors

  • Constructors: Use constructors to set up initial values for your objects or to perform actions that are necessary before the object is used.

  • Destructors: Use destructors for cleanup activities, like releasing resources or closing connections. However, in Python, due to its garbage collection, destructors are not as critical as in languages like C++.


3.2.7 - Class Examples

3.2.7.1 - Example 1: Employee Class

class Employee:
def __init__(self, name, position):
self.name = name
self.position = position

def introduce(self):
print(f"My name is {self.name} and I am a {self.position}.")

# Creating an object
emp1 = Employee("Alice", "Engineer")
emp1.introduce() # Output: My name is Alice and I am an Engineer.

3.2.7.2 - Example 2: Book Class

class Book:
def __init__(self, title, author):
self.title = title
self.author = author

def describe(self):
print(f"The book '{self.title}' is written by {self.author}.")

# Creating an object
book1 = Book("1984", "George Orwell")
book1.describe() # Output: The book '1984' is written by George Orwell.

3.2.7.3 - Example 3: Library Management System

class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.is_checked_out = False

def check_out(self):
if not self.is_checked_out:
self.is_checked_out = True
return True
else:
return False

def check_in(self):
if self.is_checked_out:
self.is_checked_out = False
return True
else:
return False

class Member:
def __init__(self, name):
self.name = name
self.books_checked_out = []

def borrow_book(self, book):
if book.check_out():
self.books_checked_out.append(book)
print(f"{self.name} has borrowed {book.title}.")
else:
print(f"{book.title} is currently not available.")

def return_book(self, book):
if book in self.books_checked_out:
book.check_in()
self.books_checked_out.remove(book)
print(f"{self.name} has returned {book.title}.")
else:
print(f"{self.name} does not have {book.title}.")

class Library:
def __init__(self):
self.books = []
self.members = []

def add_book(self, book):
self.books.append(book)

def add_member(self, member):
self.members.append(member)

def show_available_books(self):
available_books = [book.title for book in self.books if not book.is_checked_out]
print("Available Books: " + ", ".join(available_books))

# Usage
library = Library()
book1 = Book("1984", "George Orwell", "123456789")
book2 = Book("To Kill a Mockingbird", "Harper Lee", "987654321")
member1 = Member("Alice")

library.add_book(book1)
library.add_book(book2)
library.add_member(member1)

member1.borrow_book(book1)
library.show_available_books()
member1.return_book(book1)
library.show_available_books()

3.2.7.4 - Example 4: Online Store

class Product:
def __init__(self, name, price):
self.name = name
self.price = price

class ShoppingCart:
def __init__(self):
self.products = []

def add_product(self, product):
self.products.append(product)

def remove_product(self, product):
if product in self.products:
self.products.remove(product)

def calculate_total(self):
return sum(product.price for product in self.products)

class Customer:
def __init__(self, name):
self.name = name
self.cart = ShoppingCart()

def add_to_cart(self, product):
self.cart.add_product(product)
print(f"{product.name} added to cart.")

def checkout(self):
total = self.cart.calculate_total()
print(f"{self.name}'s total checkout amount is ${total}.")

# Usage
customer = Customer("Bob")
product1 = Product("Laptop", 1200)
product2 = Product("Headphones", 150)

customer.add_to_cart(product1)
customer.add_to_cart(product2)
customer.checkout()

3.2.7.5 - Example 5: Bank Account Management

class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance

def deposit(self, amount):
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}.")

def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}.")
else:
print("Insufficient funds.")

class Customer:
def __init__(self, name):
self.name = name
self.accounts = []

def open_account(self, account):
self.accounts.append(account)
print(f"{self.name} has opened a new account with number {account.account_number}.")

class Bank:
def __init__(self, name):
self.name = name
self.customers = []

def add_customer(self, customer):
self.customers.append(customer)

# Usage
bank = Bank("MyBank")
customer1 = Customer("John Doe")
account1 = BankAccount("12345", 1000)

bank.add_customer(customer1)
customer1.open_account(account