Understanding Classes and Objects in Python

 Understanding Classes and Objects in Python

Python is an object-oriented programming (OOP) language, which means it allows developers to create and work with objects. Understanding classes and objects is fundamental to mastering Python. In this blog, we will explore these concepts with practical examples.


What Are Classes and Objects?

A class is a blueprint for creating objects. It defines attributes (variables) and behaviors (methods) that its objects will have.

An object is an instance of a class. It contains real values assigned to the attributes defined in the class blueprint.


1️⃣ Creating a Simple Class and Object

Let's start with a simple example of a class Addition, which adds two numbers:

class Addition:
    first = 10
    second = 20

    def addNumber(self):
        c = self.first + self.second  # Using self to access class variables
        print(c)

# Creating an object
obj = Addition()

# Calling the method
obj.addNumber()  # Output: 30

Explanation:

  • The class Addition has two class variables: first and second.

  • The addNumber method adds these two variables and prints the result.

  • We created an object obj and called the addNumber method.


2️⃣ Working with Class Variables

We can create a class Person with some default attributes:

class Person:
    name = ""  # Default values
    age = 0
    address = ""
    mobile = ""

# Creating an object
p = Person()

# Assigning values
p.name = "Praveen"
p.age = 25
p.address = "RJ"
p.mobile = "123123"

# Printing values
print(f"Your name is {p.name}")
print(f"Your age is {p.age}")
print(f"Your address is {p.address}")
print(f"Your mobile number is {p.mobile}")

Explanation:

  • Class variables (name, age, address, mobile) are shared across all objects but can be modified individually.

  • We created an object p and manually assigned values to its attributes.

  • This approach works but is not efficient if we need to create multiple objects with different values.


3️⃣ Using a Constructor (__init__)

To automatically initialize object attributes, we use a constructor method called __init__:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("John", 36)

# Printing object attributes
print(f"Name: {p1.name}, Age: {p1.age}")  # Output: Name: John, Age: 36

Why Use __init__?

  • The __init__ method initializes object attributes at the time of object creation.

  • Instead of assigning values manually, we pass values directly when creating the object (p1 = Person("John", 36)).

  • This makes code cleaner and more efficient.


4️⃣ Constructor Without Class Variables

Another way to define a class without explicitly declaring variables is:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("John", 36)

print(f"Name: {p1.name}, Age: {p1.age}")

Key Difference:

  • No need to declare class variables like name = "" and age = 0.

  • Instance variables (self.name, self.age) are created dynamically.

  • This approach is preferred for real-world applications where each object has different values.


📌 Summary

ConceptExplanation
ClassBlueprint for creating objects.
ObjectInstance of a class with real data.
Class VariablesShared by all objects (e.g., species = "Human").
Instance VariablesUnique to each object, created inside __init__.
Constructor (__init__)Initializes values automatically when an object is created.

🚀 Final Thoughts

  • Using class variables is useful when you need shared values.

  • Using __init__ constructors is better for handling multiple objects with different values.

  • Python’s OOP approach makes it easy to structure and organize code efficiently.

In the next blog, we will explore Encapsulation, Inheritance, and Polymorphism in Python OOP.

Do you have any questions? Let me know in the comments! 😊🚀

Comments

Popular posts from this blog

Mastering Django: Project and App Folder Structure

Mastering Django Template Language (DTL): A Step-by-Step Guide

How to Add Templates in Django: Step-by-Step Guide