Lesson 10 of 15

Classes

Classes

Python is fully object-oriented. A class defines a blueprint for objects — bundling data (attributes) and behavior (methods).

Defining a Class

class Dog:
    def __init__(self, name, breed):  # constructor
        self.name = name              # instance attribute
        self.breed = breed

    def bark(self):
        return f"{self.name} says: Woof!"

    def __repr__(self):               # string representation
        return f"Dog({self.name!r}, {self.breed!r})"

Creating Instances

rex = Dog("Rex", "German Shepherd")
rex.bark()   # "Rex says: Woof!"
rex.name     # "Rex"
print(rex)   # Dog('Rex', 'German Shepherd')

Special Methods (Dunder Methods)

__init__   # constructor
__repr__   # developer-friendly string
__str__    # user-friendly string
__len__    # len() support
__eq__     # == comparison
__lt__     # < comparison

Class vs Instance Attributes

class Counter:
    total = 0          # class attribute (shared)

    def __init__(self):
        self.count = 0 # instance attribute

    def increment(self):
        self.count += 1
        Counter.total += 1

Your Task

Implement a Stack class with:

  • push(item) — adds item to the top
  • pop() — removes and returns the top item (raise IndexError if empty)
  • peek() — returns top item without removing (raise IndexError if empty)
  • is_empty() — returns True if no items
  • size() — returns number of items
Pyodide loading...
Loading...
Click "Run" to execute your code.