Lesson 2: Classes & Objects

⏱ ~35 min Lesson 2 of 14 💚 Free

Now we build classes from scratch. The __init__ method initializes an object's attributes. Methods define what the object can do. The self keyword always refers to the current instance.

Key Concepts

The __init__ Method

__init__ is called automatically when you create an object. It sets up the object's initial state:
class Circle:
def __init__(self, radius):
self.radius = radius

Instance Methods

def area(self):
return 3.14159 * self.radius ** 2
Methods work on the instance's data using self. Call them: c = Circle(5); c.area() → 78.54

__str__ Method

__str__ defines how an object looks when you print it:
def __str__(self):
return f'Circle with radius {self.radius}'
Now print(c) gives a readable description.

Multiple Objects

Each object from the same class is independent. c1 = Circle(5); c2 = Circle(10). Changing c1.radius doesn't affect c2. They share the class blueprint but have their own data.

✅ Check Your Understanding

1. What does self refer to in a class method?

2. When is __init__ called?

3. What does __str__ control?