Classes and Objects Basics
In Lesson 1, you discovered WHY OOP exists. Now you'll learn the syntax for HOW to create classes and objects through hands-on experimentation, AI-guided instruction, challenging the AI, and synthesizing your understanding into reusable patterns.
Part 1: Experience Classes by Experimentation
Your Role: Code explorer discovering how Python implements objects
Before reading syntax explanations, you'll experiment with creating classes to develop intuition.
Discovery Exercise: Build Classes Step by Step
What is a class? A class is a blueprint (template) for creating objects. Think of it like a cookie cutter: the class is the cutter shape, and objects are the individual cookies you make from it. The class keyword in Python defines this blueprint.
Stage 1: The Simplest Possible Class
Let's create the simplest possible class - a blueprint with no details yet.
Create a file called class_experiments.py and run this code:
Loading Python environment...
Your task 1: Run this and document:
- What does
type(my_dog)tell you? - What does
print(my_dog)show you? (Pay attention to the memory address) - What's in
dir(my_dog)? What default methods does Python give every object?
💬 AI CoLearning Prompt
"I created an empty class with just
pass. When I inspectdir(my_dog), I see lots of methods like__init__,__str__,__dict__. Where do these come from? What's the relationship between a class and an object? Explain using a cookie-cutter analogy."
Expected Understanding: AI will explain that classes are blueprints/templates (cookie cutter), objects are instances created from them (cookies). Python gives every object default methods automatically. You'll understand the class-object relationship before coding more.

Stage 2: Add Data to Objects
Pedagogical Note: In this stage, we'll show you a way to add data to objects that WORKS but isn't the professional pattern. We're doing this deliberately so you understand WHY the proper pattern (constructors with __init__) exists. Discovery through contrast is powerful.
Now modify the code:
Loading Python environment...
Your task 2: Run this and answer:
- How do you add data to an object in Python?
- Are the objects independent? Prove it.
- What happens if you inspect
my_dog.__dict__? (This shows all attributes)
💬 AI CoLearning Prompt
"I'm adding attributes to objects using
my_dog.name = 'Max'. This works, but I have to repeat this for EVERY dog I create. For 100 dogs, that's 300+ lines of attribute assignment! How do professional developers avoid this repetition? What Python feature lets me initialize attributes automatically when creating an object? Give me a preview of the solution before I learn the syntax."
Expected Understanding: AI will preview the __init__ method (constructor) that automatically runs when you create an object. You'll see WHY constructors exist before learning HOW they work. This motivates the learning in Part 2.
Stage 3: Notice the Problem with Manual Attributes
You've seen that adding attributes manually works. Now let's see why it's problematic at scale.
Loading Python environment...
Your task 3: Before reading further, predict:
- What would solve the repetition problem?
- How could you ensure every Dog object MUST have name: str, breed: str, age: int?
- What language feature would enforce this at object creation time?
Answer Preview: The solution is the constructor (__init__ method) with type hints. You'll learn this in the next section. This discovery exercise showed you the PAIN that constructors solve.
Your Discovery Summary
Instead of manual documentation, use AI to synthesize what you learned:
💬 AI CoLearning Prompt
"Based on my experiments with creating classes and adding attributes manually, summarize these key insights:
- What's the relationship between classes and objects? (blueprint vs instance)
- How are objects independent? (each has its own memory)
- What's the pain point with manual attribute assignment? (repetition, no enforcement)
- What's the solution I'm about to learn? (constructors with init)
Give me 3 concise bullet points I can reference in Part 2."
Deliverable: Save AI's synthesis in your notes. You've discovered the problem—now you're ready to learn the solution (__init__ method) in Part 2.
Part 2: Learn Class Syntax and Constructors
Your Role: Student receiving instruction from AI Teacher
Now that you've experienced the limitations of manual attribute setting, it's time to learn the solution.

AI Teaching Prompt
Ask your AI companion:
"I've been creating Dog objects and manually adding name, breed, age attributes to each one. This is repetitive:
Loading Python environment...
How can I force every Dog to automatically initialize with name, breed, age when created? Show me the syntax and explain:
- What is the
__init__method?- What is
self?- Why does Python require explicit
selfparameter?- Show me the same dog-creating code but using init"
What You'll Learn from AI
Expected AI Response (summary):
__init__method: A special constructor that Python automatically calls when you create an objectself: Represents "the object being created." It's always the first parameterself.name = name: Creates an attribute on THIS object- Why explicit self?: Python wants you to be clear: you're setting attributes on a specific object
AI will show you:
Loading Python environment...
Convergence Activity
After AI explains, test your understanding:
Ask AI: "Show me what happens in memory when I call Dog('Max', 'Labrador', 5). Walk through step-by-step: Python creates the object, then calls __init__ with what self value?"
Deliverable: Write a summary explaining __init__, self, and why this solves the repetition problem compared to manual attribute setting.
Part 3: Challenge AI with Edge Cases
Your Role: Student teaching AI by testing its understanding
Now you'll design scenarios that test whether AI understands subtle aspects of classes and objects.
Challenge Design Pattern
Challenge 1: Object Independence
Your prompt to AI:
"I create two Dog objects:
Loading Python environment...
After this, what are:
dog1.age?dog2.age?Why didn't dog2.age change? Explain what's happening in memory that makes them separate."
Expected learning: AI will explain that each object has its own memory space for attributes. This is the fundamental power of objects.
Challenge 2: Shared Blueprint, Different Instances
Your prompt to AI:
"I have:
Loading Python environment...
How many times did Python execute the Dog class definition code? How many times did it execute
__init__? Why is this efficient?"
Expected learning: AI will explain that the class is defined once, but __init__ runs for each object creation.
Challenge 3: Default Parameters in Constructors
Your prompt to AI:
"Show me a Dog class where age is optional with a default value of 0. So:
Dog('Max', 'Labrador', 5)creates a 5-year-old dogDog('Buddy', 'Golden')creates a dog with age 0What's the syntax for default parameters in
__init__?"
Deliverable
Document your three challenges, AI's responses, and your analysis of whether AI's explanation was correct and complete.
Part 4: Build Your Class Design Pattern
Your Role: Knowledge synthesizer creating design templates
Now integrate everything into reusable patterns for designing classes.
Your Class Design Template
Create a markdown file called class_design_patterns.md with this structure:
# Class Design Patterns
## Pattern 1: Simple Data Container (Basic Constructor)
**When to use**: Class whose main job is storing related data
**Template**:
```python
class Person:
def __init__(self, name: str, age: int, email: str):
self.name = name
self.age = age
self.email = email
Key points:
- Constructor parameters match attributes
- Type hints on parameters
- Simple, focused initialization
Pattern 2: Constructor with Defaults
When to use: Some attributes are optional or have sensible defaults
Template:
Loading Python environment...
Key points:
- Required parameters first
- Optional parameters last (with defaults)
- Defaults are usually for less critical data
Pattern 3: Constructor with Validation
When to use: Data must meet certain constraints
Template:
Loading Python environment...
Key points:
- Check constraints in
__init__ - Raise exceptions for invalid data
- Prevent invalid object creation
Pattern 4: Adding Methods (Behavior)
When to use: Objects need to perform actions, not just store data
Template:
Loading Python environment...
Key points:
- Methods always have
selfas first parameter - Methods use
self.attributeto access object's data - Include type hints on return types (
-> str) - Use docstrings to explain method purpose
Pattern 5: Object Independence Verification
How to verify objects are truly independent:
Loading Python environment...
Why this matters: Confirms that each object has its own memory space.
Pattern 6: The Self Parameter Explained
Memory model:
Loading Python environment...
Key insight: self = "the specific object this method is operating on"
Pattern 7: Constructor Pattern with Multiple Attributes
Full example with all patterns:
Loading Python environment...
Quick Reference: Class vs Instance
Class: Blueprint, created once
Loading Python environment...
Instance: Actual object, created many times
Loading Python environment...
Common Mistakes and Fixes
Mistake 1: Forgetting self in methods
Loading Python environment...
Mistake 2: Not calling constructor
Loading Python environment...
Mistake 3: Forgetting self. when accessing attributes
Loading Python environment...
Testing Pattern: Verify Independence
Always test that objects are independent:
Loading Python environment...
### Validation with AI
Once your patterns are complete, validate them:
> "Review my class design patterns. Are my explanations of self and object independence accurate? What patterns am I missing? What common mistakes should I add?"
**Deliverable**: Complete `class_design_patterns.md` with patterns and quick reference guide.
---
## Try With AI
Ready to master class syntax and understand how objects manage independent state?
**🔍 Explore `__init__` and `self`:**
> "Explain __init__ and self like I'm 10 years old. Then show me a Car class with brand, model, year attributes. Create three car objects. When I call car1.display_info(), how does Python know to show car1's data, not car2's? Trace through what 'self' means in memory."
**🎯 Practice Class Design:**
> "Help me build a Product class for an e-commerce system. It needs: name, price, stock_count attributes; and methods: apply_discount(percentage), restock(quantity), is_available(). Guide me through: what goes in __init__, what are instance methods, how to validate inputs (negative price/stock)."
**🧪 Test Object Independence:**
> "Create a Counter class with value attribute (starts at 0) and increment() method. Make three counters. Increment the first twice, the second once, the third zero times. Predict final values. Then explain: why don't all counters share the same value? What makes each object independent?"
**🚀 Apply to Data Modeling:**
> "I'm building [describe your system: library, blog, game, etc.]. Help me identify one core entity and design its class. Walk me through: what attributes describe it? What actions can it perform? What should __init__ accept as parameters vs set as defaults?"
---