Python Lesson 20: Classes and Objects

🐍 Python CourseLesson 20 of 26 · 77% complete

In the last lesson you learned the basics. Now go deeper — class variables, string representation, and building real-world classes.

Class Variables vs Instance Variables

class Student:
    school = "BeginnerCoder Academy"  # class variable (shared!)
    count = 0                          # tracks total students
    
    def __init__(self, name, grade):
        self.name = name      # instance variable (unique per object)
        self.grade = grade    # instance variable
        Student.count += 1   # increment class variable
    
    def info(self):
        print(f"{self.name} | Grade: {self.grade} | School: {Student.school}")

alice = Student("Alice", "A")
bob = Student("Bob", "B")

alice.info()   # Alice | Grade: A | School: BeginnerCoder Academy
print(Student.count)  # 2

__str__ — String Representation

class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year
    
    def __str__(self):
        return f"{self.year} {self.brand} {self.model}"
    
    def is_vintage(self):
        return 2024 - self.year > 25

car = Car("Toyota", "Camry", 1995)
print(car)              # 2024 Toyota Camry (uses __str__)
print(car.is_vintage()) # True

Building a Real Class: Product

class Product:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity
    
    def __str__(self):
        return f"{self.name}: ${self.price:.2f} (qty: {self.quantity})"
    
    def total_value(self):
        return self.price * self.quantity
    
    def apply_discount(self, percent):
        self.price *= (1 - percent/100)
        print(f"New price: ${self.price:.2f}")

laptop = Product("MacBook Pro", 1999.99, 5)
print(laptop)                    # MacBook Pro: $1999.99 (qty: 5)
print(laptop.total_value())      # 9999.95
laptop.apply_discount(10)        # New price: $1799.99

🏋️ Practice Task

Create a Library class that manages books. It should have: a list of books (empty at start), add_book(title, author) method, remove_book(title) method, search(keyword) method that finds books with keyword in title, list_all() method that prints all books.

💡 Hint: Store books as list of dicts: {“title”:…, “author”:…}. Use list comprehension for search.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *