🧱 Python Object-Oriented Programming (OOP)
Estimated reading: 4 minutes 34 views

🧱 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
  • self refers 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 initializationUse global variables in class scope
Name classes with PascalCaseUse lowercase names for class names
Use self to define object variablesSkip self in methods (will error)
Keep class responsibilities focusedCram 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Classes & Objects

Or Copy Link

CONTENTS
Scroll to Top