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 toppop()— removes and returns the top item (raiseIndexErrorif empty)peek()— returns top item without removing (raiseIndexErrorif empty)is_empty()— returnsTrueif no itemssize()— returns number of items
Pyodide loading...
Loading...
Click "Run" to execute your code.