What You'll Learn
- Define a class with attributes and methods using
__init__ - Create and use object instances
- Understand
selfand instance vs. class variables - Use dunder (magic) methods like
__str__and__repr__
💻 OOP Step Simulator
Step through a BankAccount class definition and usage line by line. Watch how attributes are stored in memory.
Code
State
Output
What Is a Class?
A class is a blueprint for creating objects. It defines what data an object holds (attributes) and what it can do (methods). An object (or instance) is a specific thing created from that blueprint.
Think of a class as a cookie cutter — it defines the shape. Each cookie you cut out is an object. The cookies share the same shape (class) but can have different decorations (attribute values).
Anatomy of a Class
__init__ — The constructor method. Python calls it automatically when you create a new instance. Use it to set initial attribute values.self — A reference to the specific instance being operated on. Always the first parameter of instance methods. Python passes it automatically.Instance variables — Variables stored on each object (e.g.,
self.balance). Each instance has its own copy.Class variables — Variables shared by all instances (defined outside
__init__). Useful for constants or counters.Dunder Methods
"Dunder" means double-underscore. Python defines special meaning for many __name__ methods. The most useful for beginners:
__str__— Called byprint(obj)andstr(obj). Return a human-friendly string.__repr__— Called in the REPL or debugging. Return an unambiguous string.__len__— Called bylen(obj).__eq__— Called byobj1 == obj2.
Quick Check
1. What is the purpose of __init__?
It deletes an object from memory
It initializes an object's attributes when the object is created
It defines a class variable shared by all instances
It prints the object to the console
2. What does self refer to inside a method?
The class itself
The parent class
The specific instance the method is called on
A built-in Python keyword with no special meaning
3. Which dunder method is called when you use print(obj)?
__repr____str____init____eq__4. Two instances a = Dog("Rex") and b = Dog("Buddy") — do they share the same name attribute value?
Yes, all instances share every attribute
No, each instance has its own copy of instance variables
Only if
name is defined as a class variableIt depends on how
__init__ is written