Class Basics
Class Basics
🎯 After reading this lesson
After reading this lesson, you will be able to do the following 3 things with confidence.
- ▸✅
__init__·self· instance method fundamentals - ▸✅ Difference between class variables and instance variables
- ▸✅ Magic methods:
__repr__·__str__·__eq__
Keep the learning goals as a checklist and close the lesson once you can answer all of them.
6 Core Class Concepts — Code + Output
class = a blueprint that bundles data + behavior. Use it when you need to create multiple objects of the same shape.
1. The Simplest Class
Calling Person() creates an object. A variable simply points to that object.
2. __init__ — Constructor
What is self? = "the object that called this method" (equivalent to Java's this). Required as the first parameter of every method.
3. Methods — Object Behavior
When calling a method like c.deposit(500), use object.method(argument) — self is passed automatically.
4. __str__ — Output Format
Without __str__, you get a meaningless output like <__main__.Person object at 0x...>. It is strongly recommended to always define it.
5. Class Variables vs Instance Variables
6. Compared to Java — Much Shorter
One-Line Summary
Key idea: Use a class when you need multiple objects of the same shape. self is that object itself.
💡 Key Points
1. self refers to the instance itself
2. __init__ is the constructor (called automatically)
3. Distinguish between class variables and instance variables
Python's OOP defines objects using classes (class). __init__ is the constructor, and self is the instance reference. Inheritance is implemented as class Child(Parent):, and super() is used to call parent methods. Use @property for getters/setters, and @classmethod/@staticmethod to define class/static methods. Multiple inheritance and MRO (Method Resolution Order) are also supported.
🐍 Try It Yourself — Class Basics
🤖 Try asking AI like this
Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' make a vocabulary-driven request — that's the starting point for saving tokens.
- ▸'Apply class basics concepts to this Python code'
- ▸'Add type hints + pytest unit tests to this code'
- ▸'Check this code for PEP 8 violations related to class basics'
Why this saves tokens
Without knowing the concepts, you have to ask 'What does that mean?' after every AI response. Those follow-up questions eat tokens. Learn the concepts once and the conversation ends in a single round.