Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Classes and Objects Exercises

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.

Setup

  1. Open your terminal/command prompt
  2. Navigate to this directory
  3. Run the exercises: python classes.py
  4. Or work interactively: python3 -i classes.py

Exercises

Exercise 1: Basic Class Definition

Create a class Person with:

  • An __init__ method that takes name and age parameters
  • Instance attributes for name and age
  • A __str__ method that returns "Person(name=X, age=Y)"

Exercise 2: Simple Methods

Add methods to the Person class:

  • get_name() that returns the person's name
  • get_age() that returns the person's age
  • have_birthday() that increases age by 1
  • is_adult() that returns True if age >= 18

Exercise 3: Class with Behavior

Create a class BankAccount with:

  • __init__ method that takes account_holder and optional initial_balance (default 0)
  • deposit(amount) method that adds to the balance
  • withdraw(amount) method that subtracts from balance (if sufficient funds)
  • get_balance() method that returns current balance
  • __str__ method for readable output

Exercise 4: Class with Validation

Create a class Rectangle with:

  • __init__ method that takes width and height (must be positive)
  • get_area() method that calculates width * height
  • get_perimeter() method that calculates 2 * (width + height)
  • is_square() method that returns True if width equals height
  • Validation that raises ValueError for negative dimensions

Exercise 5: Class with Lists

Create a class ShoppingCart with:

  • __init__ method that creates an empty cart
  • add_item(item, price) method to add items
  • remove_item(item) method to remove items
  • get_total() method that calculates total price
  • get_items() method that returns list of items
  • is_empty() method that returns True if cart is empty

Exercise 6: Class Relationships

Create a class Student with:

  • __init__ method taking name and student_id
  • add_grade(subject, grade) method to track grades
  • get_grade(subject) method to retrieve a grade
  • get_gpa() method that calculates average of all grades
  • get_subjects() method that returns list of subjects

Exercise 7: Class with Class Attributes

Create a class Car with:

  • Class attribute total_cars to count all cars created
  • __init__ method taking make, model, and year
  • get_age() method that calculates age from current year
  • __str__ method for readable output
  • Class method get_total_cars() that returns the count

Exercise 8: Multiple Object Interaction

Create a class Library with:

  • __init__ method that creates empty book collection
  • add_book(title, author) method to add books
  • find_books_by_author(author) method to search
  • checkout_book(title) method to mark as checked out
  • return_book(title) method to mark as available
  • get_available_books() method to list available books

Exercise 9: Advanced Class Features

Create a class Temperature with:

  • __init__ method taking temperature in Celsius
  • Property celsius with getter and setter
  • Property fahrenheit that converts from/to Celsius
  • Property kelvin that converts from/to Celsius
  • __str__ method showing all three scales

Testing Your Code

# 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

Python Class Features

  • 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

Tips

  • Always include self as 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