π§± 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 :
