Python Classes & Objects – OOP Foundation Explained
Introduction – Why Use Classes and Objects in Python?
Python supports object-oriented programming (OOP), which organizes code into classes (blueprints) and objects (instances). This approach:
- Promotes reusability and modularity
- Makes code easier to manage
- Reflects real-world entities in your codebase
From web applications to data models and APIs, classes and objects are the building blocks of robust Python programs.
In this guide, you’ll learn:
- What classes and objects are in Python
- How to define and use them
- Special methods like
__init__() - Accessing and modifying object attributes
- Best practices and real-world examples
What Is a Class in Python?
A class is a blueprint for creating objects. It defines attributes (variables) and behaviors (methods) that the objects created from the class will have.
🧍 What Is an Object?
An object is an instance of a class. It holds actual values for the attributes defined in the class.
Defining a Class and Creating an Object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I'm {self.age} years old."
Creating an Object
person1 = Person("Alice", 30)
print(person1.greet())
Output:
Hello, my name is Alice and I'm 30 years old.
Understanding __init__() Constructor
__init__()is a constructor method- Automatically called when a new object is created
selfrefers to the current object
def __init__(self, brand):
self.brand = brand
Object Attributes and Methods
Accessing Attributes
print(person1.name) # Alice
print(person1.age) # 30
Modifying Attributes
person1.age = 31
print(person1.greet()) # Updated age
Adding Attributes Dynamically
person1.city = "New York"
print(person1.city) # New York
Multiple Objects from the Same Class
person2 = Person("Bob", 25)
print(person2.greet()) # Hello, my name is Bob and I'm 25 years old.
Each object has its own copy of data.
Class vs Instance Variables
class Product:
tax = 0.1 # class variable
def __init__(self, price):
self.price = price # instance variable
def final_price(self):
return self.price + (self.price * Product.tax)
Class Methods and Static Methods
class MyClass:
@classmethod
def class_info(cls):
print("This is a class method.")
@staticmethod
def static_info():
print("This is a static method.")
Real-World Example – Bank Account
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient balance.")
def get_balance(self):
return self.balance
acc = BankAccount("Alice", 1000)
acc.deposit(500)
acc.withdraw(300)
print(acc.get_balance()) # 1200
Best Practices for Classes & Objects
| Do This | Avoid This |
|---|---|
Use __init__ for initialization | Use global variables in class scope |
| Name classes with PascalCase | Use lowercase names for class names |
Use self to define object variables | Skip self in methods (will error) |
| Keep class responsibilities focused | Cram unrelated logic into one class |
Summary – Recap & Next Steps
Python’s classes and objects let you model real-world systems, organize code cleanly, and re-use logic effectively. With __init__(), attributes, methods, and instantiation, you can start building anything from APIs to simulations.
Key Takeaways:
- Classes define structure; objects are real instances
- Use
__init__()to initialize object state - Access and modify object attributes using dot notation
- Create multiple objects from the same class
Real-World Relevance:
Used in web development (Django, Flask), GUI apps, game design, machine learning models, and more.
FAQ – Python Classes & Objects
What’s the difference between a class and an object?
A class is a template; an object is an instance of that template with real data.
What is self in Python?
self refers to the current object. It’s required to access instance attributes and methods.
Can I create multiple objects from one class?
Yes. Each object will have its own data.
p1 = Person("A", 25)
p2 = Person("B", 30)
What’s the use of __init__()?
It initializes the object when it’s created. Think of it as a constructor.
Can I have optional parameters in a class?
Yes, just assign default values:
def __init__(self, name, age=18):
...
Share Now :
