This directory contains exercises to help you practice creating and using classes and objects in Python. Classes are blueprints for creating objects that group related data and behavior together.
- Open your terminal/command prompt
- Navigate to this directory
- Run the exercises:
python classes.py - Or work interactively:
python3 -i classes.py
Create a class Person with:
- An
__init__method that takesnameandageparameters - Instance attributes for
nameandage - A
__str__method that returns "Person(name=X, age=Y)"
Add methods to the Person class:
get_name()that returns the person's nameget_age()that returns the person's agehave_birthday()that increases age by 1is_adult()that returns True if age >= 18
Create a class BankAccount with:
__init__method that takesaccount_holderand optionalinitial_balance(default 0)deposit(amount)method that adds to the balancewithdraw(amount)method that subtracts from balance (if sufficient funds)get_balance()method that returns current balance__str__method for readable output
Create a class Rectangle with:
__init__method that takeswidthandheight(must be positive)get_area()method that calculates width * heightget_perimeter()method that calculates 2 * (width + height)is_square()method that returns True if width equals height- Validation that raises ValueError for negative dimensions
Create a class ShoppingCart with:
__init__method that creates an empty cartadd_item(item, price)method to add itemsremove_item(item)method to remove itemsget_total()method that calculates total priceget_items()method that returns list of itemsis_empty()method that returns True if cart is empty
Create a class Student with:
__init__method takingnameandstudent_idadd_grade(subject, grade)method to track gradesget_grade(subject)method to retrieve a gradeget_gpa()method that calculates average of all gradesget_subjects()method that returns list of subjects
Create a class Car with:
- Class attribute
total_carsto count all cars created __init__method takingmake,model, andyearget_age()method that calculates age from current year__str__method for readable output- Class method
get_total_cars()that returns the count
Create a class Library with:
__init__method that creates empty book collectionadd_book(title, author)method to add booksfind_books_by_author(author)method to searchcheckout_book(title)method to mark as checked outreturn_book(title)method to mark as availableget_available_books()method to list available books
Create a class Temperature with:
__init__method taking temperature in Celsius- Property
celsiuswith getter and setter - Property
fahrenheitthat converts from/to Celsius - Property
kelvinthat converts from/to Celsius __str__method showing all three scales
# Example tests
person = Person("Alice", 25)
print(person) # Should show Person(name=Alice, age=25)
print(person.is_adult()) # Should return True
account = BankAccount("Bob", 100)
account.deposit(50)
print(account.get_balance()) # Should return 150
rect = Rectangle(4, 5)
print(rect.get_area()) # Should return 20
print(rect.is_square()) # Should return False
cart = ShoppingCart()
cart.add_item("Apple", 1.50)
print(cart.get_total()) # Should return 1.50- init method: Constructor for initializing objects
- self parameter: Reference to the current object instance
- Instance attributes: Data that belongs to each object
- Class attributes: Data shared by all instances
- Properties: Pythonic getters/setters using @property decorator
- str method: Defines how objects appear when printed
- repr method: Defines unambiguous object representation
- Always include
selfas the first parameter in instance methods - Use
__init__to set up initial object state - Implement
__str__for readable object output - Use properties for computed values or validation
- Name private attributes with leading underscore:
self._private - Use docstrings to document your classes and methods