Python - OOP Basics
Overview
Estimated time: 35–45 minutes
Define classes, use instance/class/static methods, create computed attributes with @property, and simplify data containers with dataclasses.
Learning Objectives
- Define a simple class with methods and attributes.
- Use @property for validation/computed values.
- Create lightweight data containers with @dataclass.
Prerequisites
Classes and methods
class Counter:
def __init__(self, start=0):
self.value = start
def inc(self):
self.value += 1
c = Counter()
c.inc()
print(c.value)
Expected Output: 1
@property
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full_name(self):
return f"{self.first} {self.last}"
p = Person("Ann", "Lee")
print(p.full_name)
Expected Output: Ann Lee
Dataclasses
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
pt = Point(3, 4)
print(pt)
Expected Output: Point(x=3, y=4)
Common Pitfalls
- Forgetting self in instance method definitions.
- Mutating shared class attributes when you meant instance attributes.
Checks for Understanding
- What is @property used for?
- How does @dataclass help compared to writing __init__ manually?
Show answers
- To expose computed/validated attributes via attribute access syntax.
- It auto-generates boilerplate like __init__, __repr__, and comparisons.
Exercises
- Create a Rectangle class with width/height and an area @property.
- Make a dataclass for a Task with title and done flag; print friendly text.