python / python-control-flow
20 mins
Python Level 7: Classes, Objects & self Binding
Why This Matters: Classes encapsulate state and behavior into reusable software objects.
## Object-Oriented Programming in Python
Classes define blueprints for objects.
```python
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def is_passing(self):
return self.score >= 60
s = Student("Maya", 88)
print(f"{s.name} Passing: {s.is_passing()}")
```
MENTAL MODEL & MEMORY LAYOUT
INSTANTIATION MODEL:
Student("Maya", 88) ──► Allocates instance ──► Binds self.name="Maya", self.score=88 COMMON PITFALLS TO AVOID
- Forgetting `self` parameter in instance method declarations.
Class Inheritance Pattern
class Animal:
def speak(self):
return "Generic Sound"
class Dog(Animal):
def speak(self):
return "Woof!"
d = Dog()
print(d.speak()) # Outputs Woof!Subclass overrides parent method implementation.
CONCEPT MASTERY CHECKPOINT
In Python class methods, what does the `self` parameter represent?
NEXT RECOMMENDED LESSON
Python Level 8: Problem Solving & Hash Maps
Challenge: Create class Circle with radius attribute and area() method.