Classes & Objects
Overview
Classes are blueprints for creating Custom Objects. Object-Oriented Programming (OOP) allows you to bundle state (data/attributes) and behavior (functions/methods) into a single, cohesive entity. This paradigm represents real-world entities cleanly. A Class defines the structure, while an Object (or Instance) is an actual realized version of that structure in memory.
Syntax
class Dog:
# Class Attribute: Shared by ALL instances globally
species = "Canis familiaris"
# The Constructor: Initializes Instance Attributes
def __init__(self, name, age):
self.name = name # Unique to each instance
self.age = age
# Instance Method: Behavior
def bark(self):
print(f"{self.name} says Woof!")
# Instantiating Objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)
print(dog1.species) # Canis familiaris
dog2.bark() # Lucy says Woof!Common Pitfalls
Defining a mutable Class Attribute (like a list) and modifying it via an instance. Because Class Attributes are shared globally, altering
dog1.tricks.append('sit')will magically add 'sit' to every single dog instance in existence.Forgetting to include
selfas the first parameter of an instance method. Calling the method will throw a TypeError.
Interview Questions
What is the core difference between a Class Attribute and an Instance Attribute?
A Class Attribute is defined outside the constructor and is shared universally by all objects of that class. An Instance Attribute is defined inside __init__ using self and is completely unique to that specific object.
Real-World Example
Representing a user session in a backend application.
class UserSession:
def __init__(self, username, ip_address):
self.username = username
self.ip = ip_address
self.is_active = True
def logout(self):
self.is_active = False
print(f"Session closed for {self.username}")Check Your Knowledge
Test your understanding of Classes & Objects with these quick questions.