PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. Python Basics
  2. Python: Object Oriented Programming (OOP)
  • Python

  • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets

On this page

  • 1 Overview
  • 2 Object Oriented Programming (OOP)
  • 3 Python Classes and Objects
  • 4 Object intuiton
    • 4.1 Example 1
    • 4.2 Example 2
    • 4.3 Example 3
  • 5 __init__()
  • 6 self
  • 7 Class attributes
  • 8 Class methods
  • 9 Creating an Object
  • 10 More methods
  • 11 Multiple instances
  • 12 Dunder (double underscore) methods
  • 13 str
  • 14 Operator Overloading
  • 15 Managing Invoices
  • 16 Exercises
    • 16.1 Circle and Rectangle
    • 16.2 Shopping Cart
    • 16.3 Flight Booking System
    • 16.4 Sports League
    • 16.5 School Management
    • 16.6 Robot Dance Party
    • 16.7 Inventory Management System
  • Edit this page
  • View source
  • Report an issue
  1. Python Basics
  2. Python: Object Oriented Programming (OOP)

Python: Object Oriented Programming (OOP)

Python Object Oriented Programming (OOP)

python
oop
objects
Python Object Oriented Programming (OOP)
Author

Isaac Boixaderas

Published

Sunday, June 1, 2025

Modified

Sunday, November 16, 2025

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.

OOP in python

OOP in python

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:
variable = str()   # Equivalent to: variable = ''

4.3.1 String class:

  • Attributes
    • __doc__
    • __class__
    • …
  • Methods
    • lower()
    • replace()
    • count()
    • …

  • Defining a Product class in Python (preferably in upper camel case):
  • The Product class definition is the blueprint.
  • p1 and p2 are different instances of product built from the blueprint.
class Product:
    pass

p1 = Product()
p2 = Product()

print(p1)
<main.Product object at 0x7c2b933f7c10>

5 __init__()

  • Automatically called when a new object is created.
  • Initializes object attributes.
  • Why double underscores (__)?
  • What is this self?
class Product:

    def __init__(self, name, quantity=1):
        self.name = name
        self.quantity = quantity
        self.active = True

Cake
1
True

6 self

  • Refers to the object instance being created.
  • Used to access object attributes.
  • Think of self as a way to refer to the object instance itself.
Milk

And the other does not change, because name is in the self:

print(p2.name)
Soup

You can also add new attributes to the self without affecting other instances:

p1 = Product('Cake', 5)
p2 = Product('Soup', 2)

p1.brand = 'Pascual'

print(p1.brand)
Pascual

print(p2.brand)
AttributeError: ‘Product’ object has no attribute ‘brand’

7 Class attributes

Are shared among all object instances.

class Product:
    tax_rate = 0.21   # class attribute

    def __init__(self, name, quantity=1):
        self.name = name
        self.quantity = quantity
        self.active = True
  • If you change a class attribute, all instances change:
Product.tax_rate = 0.1

print(p1.tax_rate)
print(p2.tax_rate)
0.1
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_rate has no impact on p1 anymore.
p1.tax_rate = 0.4  # creates tax_rate instance attribute

print(p1.tax_rate)
print(p2.tax_rate)
0.4
0.1

Parameter names in the __init__() function can have any name, they do not necesseraly have to be named equal to the :

class Product:
    def __init__(self, n, q=1):
        self.name = n
        self.quantity = q

8 Class methods

  • Functions that define actions an object can take.
  • self always has to be the first parameter, as all methods can access it.
  • For example, update_stock:
class Product:

    def __init__(self, name, quantity=1):
        self.name = name
        self.quantity = quantity

    def update_stock(self, amount):
        self.quantity += amount
        print(f'New quantity: {self.quantity}')

9 Creating an Object

Instantiate (build) using the class blueprint.

cake = Product('Cake')

What is happening internally?

  1. Memory is allocated for the new object.
  2. __init__() method is called automatically.
  3. Attributes set within __init__() are initialized.
  4. The new object (with its initialized attributes) is returned and assigned to the variable (cake in this case).

When a method changes an attribute in the self, it changes everywhere:

cake.update_stock(5)
New quantity: 6
cake.update_stock(-2)
New quantity: 4
print(cake.quantity)
4

Note that…

  • Notice that we don’t write self when calling an object’s methods.
  • However, every instance method must include self as 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}€')

cake = Product('Cake', unit_price=1.79, quantity=10)

cake.describe()
Cake
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.
carrot = Product('Carrot', 'Ametller', unit_price=0.1)
pizza = Product('Pizza', 'Buittoni', unit_price=3.95, quantity=20)

carrot.describe()
pizza.describe()
I’m Carrot from Ametller.
Quantity: 1
Unit price: 0.1€
I’m Pizza from Buittoni.
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:
pizza = Product('Pizza', unit_price=3.95, quantity=20)

print(pizza)
<main.Product object at 0x7a3a16288af0>

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}'

pizza = Product('Pizza', unit_price=3.95, quantity=20)

print(pizza)
Pizza: 20

14 Operator Overloading

  • Using standard operators (like +, -, *) with custom logic for objects.
  • Intuitive operations for custom objects.
  • By default, we cannot add object instances:
pizza + pizza
TypeError: unsupported operand type(s) for +: ‘Product’ and ‘Product’

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.")

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

print(new_pizza.unit_price)
3.95

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 + pizza3
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 as name, position, and performance_score.
  • Class Team: should include attributes like team_name and a list of Player objects.
  • 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 as course_name and course_code.
  • Class Student: should include attributes like student_id, name, and enrolled_courses (a list of Course objects).
  • External function is_enrolled(student, course_code): this function must not be part of any class. It should receive a Student object and a course_code, and return True if the student is enrolled in that course, or False otherwise.

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 RobotDancer objects.
    • 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’s dance() method. Print a special message in case there are no robots on the dance floor.

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).
Back to top
Python: None keyword in Python
Python: Inheritance and Polymorphism

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue