What is a Class?
A template that defines the structure and behavior of objects.
Attributes
Variables that store object data
self.name = "Buddy"
Stored in each object's memory
Methods
Functions that define behavior
def bark(self): print("Woof!")
Operate on the object's data
Class Declaration Syntax
class ClassName: def __init__(self, params): # Constructor self.attr = params # Attribute init def method_name(self): # Method # Function body
Practical Implementation
class User:
def __init__(self, username, email):
self.username = username # String attribute
self.email = email # String attribute
self.login_count = 0 # Integer attribute
def login(self): # Method
self.login_count += 1
print(f"{self.username} logged in")
→ Usage: user1 = User("alice", "alice@example.com")
→ Key Point: Attributes define state, methods define behavior.
Class vs Module: When to Use Each
| Classes | Modules |
|---|---|
class DataProcessor:
def __init__(self, data):
self.data = data
|
# processor.py
def clean_data(data):
return data.strip()
|
|
|
Pro Tip: Use modules for utilities, classes when you need to create objects with identity.
Objects (Instances)
Concrete individual units created from a class blueprint.
Instantiation
my_dog = Dog("Buddy", 3) # Creates object
print(my_dog.name) # Access attribute
Object Identity
print(id(my_dog)) # Unique memory address print(type(my_dog)) # Returns: <class '__main__.Dog'>
age: 3
__class__: Dog
Instance Mutability
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
# Modify instance attribute
dog1.age = 4
Key Behavior:
- Changes to
dog1don't affectdog2 - Each object maintains independent state
Practical Usage Patterns
Collections of Objects
dogs = [Dog("Buddy", 3),
Dog("Max", 5)]
Object as Arguments
def print_dog_age(dog_obj):
print(dog_obj.age)
Dynamic Attributes
dog1.breed = "Golden" # Added at runtime
The __init__ Method
The constructor that initializes new object instances.
Automatic Execution Timeline
my_obj = MyClass()→ Python allocates memory__new__method creates raw object (implicit)__init__initializes object state- Reference assigned to
my_obj
Required Parameters
class User:
def __init__(self, username): # Mandatory
self.username = username
# user = User() # ERROR: missing username
Forgetting arguments raises TypeError
Default Values
class Account:
def __init__(self, balance=0): # Optional
self.balance = balance
acc = Account() # Uses balance=0
Default args enable flexible instantiation
Type Validation
def __init__(self, name: str):
if not isinstance(name, str):
raise TypeError("Name must be string")
self.name = name
Computed Attributes
def __init__(self, first, last):
self.fullname = f"{first} {last}" # Derived value
Critical Mistakes
❌ Mutable Default Arguments
def __init__(self, items=[]): # Dangerous!
self.items = items
All instances share the same list. Use None instead.
❌ Forgetting self
def __init__(name): # Missing self
self.name = name
Raises TypeError: __init__() takes 1 positional argument...
Instance vs. Class Attributes
Understand where data lives and how it's shared.
class Dog:
def __init__(self, name):
self.name = name # Per-instance
dog1 = Dog("Buddy")
dog2 = Dog("Max")
- Stored in individual objects
- Unique to each instance
- Defined in
__init__or methods
class Dog:
species = "Canis familiaris" # Shared
dog1 = Dog()
dog2 = Dog()
- Stored in the class itself
- Shared across all instances
- Defined at class level
Memory Allocation
Class attributes exist once in memory, instance attributes are per-object
Shadowing Class Attributes
class Dog:
species = "Canis familiaris"
dog1 = Dog()
dog1.species = "Felis catus" # Creates instance attribute
print(Dog.species) # Original unchanged: "Canis familiaris"
Instance assignment doesn't modify class attribute
Dynamic Class Changes
Dog.species = "Canis lupus" # Affects all instances print(dog1.species) # "Canis lupus" (if no shadowing) print(dog2.species) # "Canis lupus"
Class-level changes propagate to instances
When to Use Each
✅ Use Instance Attributes For:
- Object-specific state (name, age, balance)
- Mutable data unique to each instance
✅ Use Class Attributes For:
- Constants (DEFAULT_SIZE, MAX_LIMIT)
- Shared configuration across instances
Common Mistakes
1. Missing self Parameter
class Dog:
def bark(): # Missing self
print("Woof!")
❌ Error Triggered:
TypeError: bark() takes 0 positional arguments but 1 was given
Python automatically passes the instance as first argument.
✅ Fix:
def bark(self):
All instance methods must take self as first parameter.
2. Mutable Default Arguments
class ShoppingCart:
def __init__(self, items=[]): # Dangerous!
self.items = items
❌ Hidden Behavior:
cart1 = ShoppingCart()
cart1.items.append("Apple")
cart2 = ShoppingCart()
print(cart2.items) # ['Apple'] 😱
Default list is created once at class definition.
✅ Fix:
def __init__(self, items=None):
self.items = items or []
Use None and initialize per-instance.
3. Class vs Instance Attribute Confusion
class Counter:
count = 0 # Class attribute
def increment(self):
self.count += 1 # Accidentally creates instance attr
❌ Unexpected Output:
c1 = Counter() c1.increment() c2 = Counter() print(c2.count) # 0 (Expected 1)
+= creates new instance attribute instead of modifying class attr.
✅ Fix:
def increment(self):
Counter.count += 1 # Explicit class reference
Or use @classmethod for class-level operations.
You're Now a Class Designer!
In this lesson, you've transformed from writing procedural scripts to architecting object-oriented systems. You can now:
- Design classes that logically bundle data and behavior
- Instantiate objects with independent state
- Leverage __init__ for clean object initialization
- Choose between class vs instance attributes strategically
Expand Your Knowledge
Dive deeper into technology and productivity with these related articles:
- Understanding IT – Build a solid foundation in Information Technology essentials.
- Introduction to Python – Learn Python, one of the most in-demand programming languages.
- Prompt Engineering: Writing Effective AI Prompts – Master the skill of crafting precise AI prompts for better results.
- Understanding Brain Rot in the Digital Age – Break free from digital overload and regain focus.
- Effective Study Techniques for Better Learning – Discover research-backed strategies to boost learning retention.
Test Your Knowledge
Validate your understanding of classes with a quiz.
No comments yet. Be the first to share your thoughts!