Object-oriented Python concepts using a bookstore scenario.
This lab will focus on key object-oriented principles such as
classes: recipes, templates that model real world entities (tangible or intangible such as relationships)
objects: instances of classes
inheritance: a way of connecting classes together based on abstraction
object composition: objects have data fields:
simple primitive data type: string, number arrays, or other datastructures let us model collections of related objects illustrating how these concepts can be used to model real-world scenarios.
The bookstore example is relatable and offers a rich context for exploring these concepts.
### Python Lab: Object-Oriented Programming with a Bookstore Model
#### Objective:
To understand and apply object-oriented programming concepts in Python, focusing on:
class creation
object instantiation
inheritance
object composition
using a bookstore model.
#### Prerequisites:
- Basic knowledge of Python syntax (variables, loops, functions).
- Python 3.x installed on the system.
- Text editor or IDE (like VSCode, PyCharm, etc.).
#### Lab Structure:
**Part 1: Introduction to Object-Oriented Programming**
1. **Basic Concepts**
- Lecture or reading material on classes, objects, attributes, methods, and inheritance.
- Discuss the principles of object-oriented programming.
2. **Creating a Simple Class**
- Task: Create a `Book` class with attributes like `title`, `author`, `price`.
- Include a constructor (`__init__` method) and a method to display book details.
////
Below is an example of how you can create a simple `Book` class in Python, fulfilling the specified requirements:
```python
class Book:
def __init__(self, title, author, price):
"""
#Constructor for the Book class.
:param title: A string representing the title of the book.
:param author: A string representing the author of the book.
:param price: A float representing the price of the book.
"""
self.title = title
self.author = author
self.price = price
def display_book_details(self):
"""
Method to display the details of the book.
"""
print(f"Book Details:\nTitle: {self.title}\nAuthor: {self.author}\nPrice: ${self.price:.2f}")
# Example usage:
# Creating OBJECTS/ instance of the Book class
my_book = Book("1984", "George Orwell", 15.99)
# Displaying the details of the book
my_book.display_book_details()
```
### Explanation:
- **Class Definition**: The `Book` class is defined with the keyword `class`.
- **Constructor (`__init__` method)**: This special method is used to initialize the attributes of the class. It takes `self`, `title`, `author`, and `price` as parameters.
- **Attributes**: `self.title`, `self.author`, and `self.price` are instance attributes. They are associated with each instance of the `Book` class.
- **Display Method**: `display_book_details` is a method that prints the details of the book. It formats the price to two decimal places.
- **Creating an Instance**: `my_book` is created as an instance of the `Book` class with the title "1984", author "George Orwell", and price 15.99.
- **Using the Display Method**: The `display_book_details` method is called on the `my_book` instance to print its details.
This code provides a basic structure for a `Book` class and demonstrates how to create an instance and use its methods. It can be further expanded or modified as needed for more complex applications.
////
**Part 2: Expanding the Model with More Classes**
1. **Creating Customer and Purchase Classes**
- Task: Define a `Customer` class with attributes like `name`, `email`.
- Define a `Purchase` class that includes a `Customer` object and a list of `Book` objects.
2. **Understanding Relationships**
- Discuss how `Purchase` is a composition of `Customer` and `Book` objects.
- Explain the concept of object composition and its advantages.
---
/////
Arrays:
See sample code here:
///
A pre-facing exercise that focuses on Python arrays (more commonly known as lists in Python) is an excellent way to prepare students for understanding object collections, such as a list of book objects.
This exercise will cover the construction and basic operations on Python lists.
### Python Exercise: Introduction to Python Lists
#### Objective:
To familiarize students with Python lists, their creation, and basic methods for manipulating them.
#### Prerequisites:
- Basic knowledge of Python syntax (variables, loops, basic functions).
- Python 3.x installed on the system.
- Text editor or IDE (like VSCode, PyCharm, etc.).
#### Exercise Outline:
**Part 1: Basics of Python Lists**
1. **Creating Lists**
- Task: Create a list of numbers and a list of strings.
- Example: `numbers = [1, 2, 3, 4, 5]` and `fruits = ["apple", "banana", "cherry"]`.
2. **Accessing List Elements**
- Task: Access and print different elements from the lists.
- Example: Print the first and last elements of the `numbers` list.
3. **Modifying Lists**
- Task: Add, remove, and modify elements in a list.
- Example: Add a new fruit to `fruits`, remove an element from `numbers`.
---
**Part 2: Working with Lists**
1. **Iterating Over Lists**
- Task: Use a loop to iterate through the `fruits` list and print each fruit.
2. **List Comprehensions**
- Task: Create a new list that contains only the even numbers from the `numbers` list using list comprehension.
3. **Basic List Methods**
- Task: Explore methods like `append`, `remove`, `sort`, and `reverse`.
- Example: Sort the `fruits` list and then reverse it.
---
**Part 3: Advanced List Operations**
1. **Nested Lists**
- Task: Create a nested list (a list of lists) and access its elements.
- Example: `matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]` and access an element like `matrix[1][2]`.
2. **Slicing Lists**
- Task: Use slicing to create sublists.
- Example: Create a sublist of `numbers` containing only the first three elements.
3. **List Functions**
- Task: Use built-in functions like `len`, `max`, `min`, and `sum` with lists.
- Example: Find the length of `fruits` and the sum of `numbers`.
---
#### Additional Tasks for Practice:
- **Combining Lists**: Combine (concatenate) two lists into one larger list.
- **List to String Conversion**: Convert a list of characters into a string using `join`.
- **Filtering Lists**: Use the `filter` function to filter out elements based on a condition.
#### Evaluation:
- Review the lists created and the operations performed on them.
- Check for understanding by asking students to explain how they would use lists in different scenarios.
- Assess understanding through a short quiz or hands-on problem-solving session.
#### Additional Resources:
- Provide links to official Python documentation on lists.
- Suggest interactive Python tutorials or exercises available online for further practice.
This exercise will set a solid foundation for understanding how lists work in Python, which is crucial for managing collections of objects like books in a bookstore scenario. Understanding these concepts will significantly help in grasping more complex topics like object collections and operations on them.
///
To create a factory method
that generates 10 book instances, we first need to modify the `Book` class slightly. Then, we will add a separate function (the factory method) that will create and return a list of 10 `Book` instances.
Here's the updated `Book` class and the factory method:
```python
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def display_book_details(self):
print(f"Book Details:\nTitle: {self.title}\nAuthor: {self.author}\nPrice: ${self.price:.2f}")
def create_book_list():
"""
Factory method to create a list of 10 Book instances.
"""
books = []
for i in range(1, 11):
book = Book(f"Title {i}", f"Author {i}", i * 10.0)
books.append(book)
return books
# Using the factory method to create 10 books
book_list = create_book_list()
# Displaying details of each book
for book in book_list:
book.display_book_details()
print() # Just to add a blank line between book details for better readability
```
### Explanation:
- **Factory Method (`create_book_list`)**: This function creates 10 `Book` instances. Each book is given a title, an author, and a price. The title and author are generated using the loop variable `i` (e.g., "Title 1", "Author 1", ...), and the price is set as `i * 10.0`.
- **Creating Books**: Inside the loop, a new `Book` instance is created and appended to the `books` list.
- **Return Value**: After all 10 books are created, the list `books` is returned.
- **Displaying Book Details**: After creating the 10 books using the factory method, we iterate through the `book_list` and call `display_book_details` on each book to print their details.
This setup allows you to easily generate a predefined number of `Book` instances and can be modified to suit different requirements, such as varying the number of books or dynamically generating titles and authors.
/////
**Part 3: Implementing Object Composition**
1. **Building the Composition Relationship**
- Task: In the `Purchase` class, implement methods to add books to the purchase and calculate the total cost.
- Show how objects of `Customer` and `Book` are used within `Purchase`.
2. **Testing the Composition**
- Task: Create instances of `Customer`, multiple `Book` objects, and then a `Purchase` object combining them.
- Demonstrate the interactions between these objects.
---
**Part 4: Enhancing the Bookstore Model**
1. **Creating a Bookstore Class**
- Task: Implement a `Bookstore` class that holds a collection of `Book` objects.
- Include methods to add books to the bookstore and search for books by various attributes.
2. **Managing Purchases in the Bookstore**
- Task: In the `Bookstore` class, add a method to handle purchases, creating `Purchase` objects.
- Discuss how this represents a real-world process in an object-oriented way.
---
**Part 5: Advanced Concepts and Best Practices**
1. **Inheritance and Polymorphism**
- Task: Create a subclass of `Book`, such as `Ebook`, with additional attributes.
- Demonstrate polymorphism and method overriding.
2. **Object-Oriented Best Practices**
- Discussion: Cover best practices in object-oriented design (like encapsulation, DRY principle).
- Encourage good commenting and documentation habits.
---
**Part 6: Mini-Project**
- **Complete Bookstore System**
- Task: Develop a comprehensive bookstore system incorporating all the discussed concepts.
- Include advanced features like user interfaces, persistent storage, or integration with an external API for book data.
---
#### Evaluation:
- Review the code written by students in each part.
- Assess their understanding through quizzes, code reviews, or practical demonstrations.
- Evaluate the mini-project based on code quality, implementation of OOP concepts, and creativity.
---
#### Additional Resources:
- Provide links to official Python documentation and tutorials on OOP.
- Suggest books or online courses for further learning.
---
This lab is designed to be interactive and progressively builds on the concepts of object-oriented programming. It aims to provide students with both the theoretical foundations and practical experience in applying these concepts to a real-world-like scenario.
//lesson 7
To implement and test the object composition in the context of the bookstore scenario, we will first define the `Customer`, `Book`, and `Purchase` classes.
We will then demonstrate how these classes can be used to create instances of customers, books, and purchases, showing the relationships between these objects.
### Implementation:
#### 1. Defining the Classes:
```python
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
class Customer:
def __init__(self, name, email):
self.name = name
self.email = email
class Purchase:
def __init__(self, customer):
self.customer = customer
self.books = []
self.total_cost = 0.0
def add_book(self, book):
self.books.append(book)
self.total_cost += book.price
def display_purchase_details(self):
print(f"Purchase details for {self.customer.name}:")
for book in self.books:
print(f"- {book.title} by {book.author}, ${book.price:.2f}")
print(f"Total Cost: ${self.total_cost:.2f}")
```
#### 2. Testing the Composition:
```python
# Creating Book Instances
book1 = Book("1984", "George Orwell", 15.99)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 12.99)
book3 = Book("The Great Gatsby", "F. Scott Fitzgerald", 10.99)
# Creating Customer Instances
customer1 = Customer("Alice Johnson", "alice@example.com")
customer2 = Customer("Bob Smith", "bob@example.com")
# Creating Purchase Instances
purchase1 = Purchase(customer1)
purchase1.add_book(book1)
purchase1.add_book(book3)
purchase2 = Purchase(customer2)
purchase2.add_book(book2)
# Displaying Purchase Details
purchase1.display_purchase_details()
print()
purchase2.display_purchase_details()
```
### Explanation:
- **Classes**: `Customer`, `Book`, and `Purchase` classes are defined. `Customer` has name and email, `Book` has title, author, and price, and `Purchase` has a customer, a list of books, and the total cost.
- **Object Composition**: In `Purchase`, we see composition in action. A `Purchase` object is composed of a `Customer` object and a list of `Book` objects. The `add_book` method adds a book to the purchase and updates the total cost.
- **Testing**:
- We create three `Book` instances (`book1`, `book2`, `book3`).
- Two `Customer` instances (`customer1` and `customer2`) are created.
- Two `Purchase` instances are made, each associated with a customer. Books are added to each purchase using the `add_book` method.
- The `display_purchase_details` method prints out the details of each purchase, showing the customer's name, the books purchased, and the total cost.
This example demonstrates how classes can be used to create complex relationships through object composition, modeling a real-world scenario in an object-oriented way.
//lesson 7
// lesson inheritance