In this tutorial, we bring you a set of Python dataclass exercises. It includes the full source code for the first two problems. The solutions are self-explanatory, yet you’ll see a summary of all the important steps.
Python dataclass exercises
Our exercises offer a hands-on exploration of Python’s dataclasses, showcasing their various features. There are a total of four data class problems that we are putting forth before you. These are not merely partial pieces of code but full-fledged Python programs. For the first two problems, we’ve provided the solution, while for the rest, you’ll have the chance to practice and write the logic yourself. Get ready to enhance your Python skills and dive into the world of data classes!
Moreover, while working on these exercises, you can follow our tutorial on Python data classes and brush up on your concepts. At any point, we are happy to support your learning process. Do contact us via comments or use the contact form from our blog.
Exercise-1:
As an illustration, create a simple program that manages student records, including their name, age, grades, and an automatically calculated average grade.
Solution:
Here’s the code:
from dataclasses import dataclass, field from typing import List @dataclass(order=True) class Student: name: str age: int grades: List[float] = field(default_factory=list) average_grade: float = field(init=False) def __post_init__(self): self.average_grade = sum(self.grades) / len(self.grades) if self.grades else 0.0 def promote(self): self.age += 1 def add_grade(self, grade): self.grades.append(grade) def __str__(self): return f"Student(name='{self.name}', age={self.age}, grades={self.grades}, average_grade={self.average_grade})" # Create instances of the Student class student1 = Student("Emma", 18, [85.5, 92.0, 78.5]) student2 = Student("Noah", 17, [90.0, 88.5]) # Access attributes print(student1.name) # Output: Emma print(student2.age) # Output: 17 print(student1.grades) # Output: [85.5, 92.0, 78.5] print(student2.average_grade) # Output: 89.25 # Modify attributes student1.promote() student1.add_grade(95.0) print(student1.age) # Output: 19 print(student1.grades) # Output: [85.5, 92.0, 78.5, 95.0] print(student1.average_grade) # Output: 87.75 # Equality comparison and ordering student3 = Student("Luca", 18, [85.5, 92.0, 78.5]) print(student1 == student3) # Output: True print(student1 < student2) # Output: False # Default values and object representation student4 = Student("Eve", 20) print(student4) # Output: Student(name='Eve', age=20, grades=[], average_grade=0.0)
Summary
In this program, we define a dataclass named Student that represents student records. It has attributes for name, age, grades, and average_grade. The grades attribute is initialized as an empty list, and the average_grade attribute is calculated using the __post_init__ method.
We also include methods like promote() to increase the student’s age and add_grade to add grades to the list. The __str__ method is overridden to provide a customized string representation of the object.
The code demonstrates various features of dataclasses, such as default values for attributes, the usage of the field function from the typing module, ordering based on attributes, and more.
Feel free to run this code and explore the functionalities of data classes in Python. It provides a concise and efficient way to work with data-centric classes, reducing boilerplate code and enhancing code readability and maintainability.
Exercise-2:
Write a program that represents a library management system using data classes in Python. We’ll define classes for books and library members, allowing us to add books to the library, lend books to members, and keep track of book availability.
Solution:
from dataclasses import dataclass, field from typing import List @dataclass class Book: title: str author: str available: bool = True @dataclass class Member: name: str books_borrowed: List[Book] = field(default_factory=list) def borrow_book(self, book): if book.available: book.available = False self.books_borrowed.append(book) print(f"{self.name} has borrowed the book '{book.title}' by {book.author}.") else: print(f"Sorry, the book '{book.title}' is currently unavailable.") def return_book(self, book): if book in self.books_borrowed: book.available = True self.books_borrowed.remove(book) print(f"{self.name} has returned the book '{book.title}' by {book.author}.") else: print(f"Error: '{book.title}' is not borrowed by {self.name}.") # Create instances of the Book class book1 = Book("Python Crash Course", "Eric Matthes") book2 = Book("Clean Code", "Robert C. Martin") book3 = Book("The Alchemist", "Paulo Coelho") # Create instances of the Member class member1 = Member("Emma") member2 = Member("Noah") # Perform book borrowing and returning member1.borrow_book(book1) member1.borrow_book(book2) member2.borrow_book(book2) member2.borrow_book(book3) member1.return_book(book2) member2.return_book(book1) member2.return_book(book3)
Summary:
In this program, we create two data classes: Book and Member. The Book class represents a book with attributes for the title, author, and available status. The Member class represents a library member with a name and a list of books_borrowed as attributes.
The Member class includes methods borrow_book() and return_book() to handle book borrowing and returning operations. When a member borrows a book, the book’s availability is updated, and the book is added to the member’s list of borrowed books. Similarly, when a member returns a book, the book’s availability is updated, and the book is removed from the member’s list.
In the main part of the code, we create instances of books and members. We then simulate book borrowing and returning operations by calling the corresponding methods on the member objects. The program outputs messages indicating successful borrowings or returns, as well as any errors encountered.
This code demonstrates how data classes can be used to model and manage objects in a library management system. It provides a simple and effective way to organize data and perform operations with minimal code, making it easier to understand and maintain the library management system.
Python dataclass exercises for practice
Here are a few more problem statements using Python dataclasses that you can try to solve:
Problem 1: Create a program to manage a student database. Each student has a name, and roll number while having enrolled for a list of subjects. Implement functionalities to add new students, display student details, and calculate the average marks of a student.
Problem 2: Design a program for a car rental agency. Create a car dataclass with attributes like make, model, year, and rental status. Implement methods to rent a car, return a car, and display the available cars.
Problem 3: Develop a program to simulate a banking system. Create dataclasses for customers and accounts. Each customer has a name and contact details, and each account has an account number, balance, and account type. Implement functionalities to create a new customer, open a bank account, perform deposits and withdrawals, and display account details.
Problem 4: Build a program for a movie ticket booking system. Create dataclasses for movies, theaters, and bookings. Each movie has a title, genre, and duration. Each theater holds a name and shows a list of currently playing movies. Implement functionalities to book a ticket, check seat availability, and display movie showtimes.
Above all, these problem statements cover a range of scenarios. Also, you can even tailor the complexity level and requirements accordingly. These exercises provide opportunities for beginners to apply data classes in real-world scenarios and practice their Python programming skills.
Summary – Python dataclass exercises
Finally, you have run through all of the above data classexercises and certainly learned a few things. If you liked it, don’t mind it sharing on social media.
By the way, if you haven’t had the chance to explore our blog’s set of 40 Python exercises for beginners, now is the perfect time to dive in. The collection comprises 10 basic, 10 intermediate, 10 advanced, and 10 expert-level exercises, catering to learners of all skill levels. Don’t miss this opportunity to challenge yourself and elevate your Python proficiency!
Happy Learning!