Skip to content

Practical Examples Classes Methods Modeling Real-World Entities Python

Updated: at 03:23 AM

Object-oriented programming (OOP) is a programming paradigm that models real-world entities using classes and objects. Python is an object-oriented language that provides constructs like classes, objects, and methods to implement OOP concepts.

Classes allow bundling together data and functionality in a single unit. They serve as templates or blueprints for creating programmatic representations of real-world objects. Methods define the behaviors and actions that can be performed on an object.

This comprehensive guide will demonstrate practical examples of using classes and methods in Python for modeling real-world objects and entities. We will cover key aspects like defining classes, creating class attributes, initializing objects, developing methods, and using object interactions.

Table of Contents

Open Table of Contents

Defining Classes in Python

A class definition starts with the class keyword, followed by the class name and a colon. The class body containing attributes and methods is indented. Here is a simple Person class example:

class Person:

  def __init__(self, name, age): = name
    self.age = age

The __init__() method is the constructor which is called automatically when a new object is instantiated. It initializes the object’s attributes using the self reference.

We can create a Person object and access its attributes:

p1 = Person("John", 36)

# Output: John

# Output: 36

Creating Class Attributes

Class attributes are variables declared inside a class definition but outside methods. They are shared by all objects of that class.

Here we add a species class attribute to Person:

class Person:
  species = "Homo Sapiens"

  def __init__(self, name, age): = name
    self.age = age

We can access it directly via the class or any object:

# Output: Homo Sapiens

p1 = Person("Mary", 25)
# Output: Homo Sapiens

Initializing Object State Using Constructors

The constructor method __init__() is called automatically when an object is created from a class. It is used to initialize the object’s state - attributes and other data.

Here we expand the constructor to take additional parameters:

class Person:

  def __init__(self, name, age, gender, occupation): = name
    self.age = age
    self.gender = gender
    self.occupation = occupation

p1 = Person("Susan", 28, "Female", "Engineer")

Now each Person instance can be uniquely initialized with a customized state.

Defining Object Methods

Methods represent the behaviors and actions that can be performed on an object. They are functions defined inside the class.

Let’s add a greet() method to Person:

class Person:

  # Class attributes
  species = "Homo Sapiens"

  # Constructor
  def __init__(self, name, age, gender, occupation): = name
    self.age = age
    self.gender = gender
    self.occupation = occupation

  # Instance methods
  def greet(self):
    print(f"Hello, my name is {}!")

p1 = Person("John", 36, "Male", "Teacher")

# Output: Hello, my name is John!

When called on an object, the greet() method has access to other attributes of that particular instance via self.

Using Object Interactions

The true power of OOP comes from interactions between objects. Objects can inspect and manipulate each other’s state and behaviors.

Let’s create a Student class that inherits from Person:

class Student(Person):

  def __init__(self, name, age, gender, occupation, school, grade):
    super().__init__(name, age, gender, occupation) = school
    self.grade = grade

  def study(self):
    print(f"{} studies in grade {self.grade} at {}.")

class Teacher(Person):

  def __init__(self, name, age, gender, occupation, subject):
    super().__init__(name, age, gender, occupation)
    self.subject = subject

  def teach(self, student):
    print(f"{} teaches {} {self.subject}.")

s1 = Student("Emma", 15, "Female", "Student", "ABC School", "10th")
t1 = Teacher("Mr. Lee", 35, "Male", "Teacher", "Math")

# Mr. Lee teaches Emma Math.
# Emma studies in grade 10th at ABC School.

Here the Student and Teacher classes inherit common attributes from Person. The teach() method takes a Student object as an argument, allowing interaction between objects.

Modeling a Retail Store System

Let’s model a simple retail store system with classes like Store, Product, Customer, and Order:

class Store:

  def __init__(self, name): = name
    self.products = []

  def add_product(self, product):

  def list_products(self):
    print(f"Available products at {}:")
    for product in self.products:

class Product:

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

  def __str__(self):
    return f"{} (${self.price})"

class Customer:

  def __init__(self, name): = name
    self.orders = []

  def place_order(self, store, *products):
    order = Order(store, self, *products)

class Order:

  def __init__(self, store, customer, *products): = store
    self.customer = customer
    self.products = list(products)

  def __str__(self):
    product_names = [ for product in self.products]
    return f"Order for {}: {product_names}"

  def calculate_total(self):
    total = 0
    for product in self.products:
      total += product.price
    return total

This implements a basic retail system with object interactions:

store = Store("ABC Supermarket")

p1 = Product("Shirt", 25)
p2 = Product("Pants", 35)
p3 = Product("Shoes", 55)


c1 = Customer("John")
c1.place_order(store, p1, p2)

# Order for John: ['Shirt', 'Pants']

order_total = c1.orders[0].calculate_total()
# 60


This guide demonstrated practical examples of using classes, objects, and methods in Python to model real-world entities. Key concepts covered include:

Object-oriented programming allows crafting code that directly represents real concepts, making it easier to design and reason about complex systems. With the principles and examples discussed in this guide, you should be able to start implementing OOP effectively in Python for various applications.