🧱 Python Classes and Objects – Build Real-World Code Structures | TechTown.in

In Python, everything is an object — even strings and numbers! But when you’re building your own applications, you can define custom objects using classes.

Classes and objects are at the heart of Object-Oriented Programming (OOP). They help you build modular, scalable, and reusable code — the foundation of every professional-grade Python project.

Let’s explore what classes and objects are, how to use them, and why they matter.


🧠 What is a Class in Python?

A class is a template or blueprint for creating objects.

Think of it like a plan for building a car. The plan isn’t the car itself — but you can build many cars (objects) from that one plan.

🧱 Example:

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

    def show_info(self):
        print(f"Name: {self.name}, Age: {self.age}")

🔍 What is an Object?

An object is an instance of a class — a real, usable entity created using that class.

s1 = Student("Tanmay", 21)
s1.show_info()

🎯 Output:

Name: Tanmay, Age: 21

🛠️ The __init__() Method

This special method runs automatically when an object is created. It’s used to initialize object properties.

def __init__(self, name):
    self.name = name

self refers to the current object being created.


📦 Object Methods

Just like variables, classes can have functions, called methods, to define object behavior.

def greet(self):
    print("Hi, my name is", self.name)

Call it like this:

s1.greet()

➕ Add Properties or Methods After Object Creation

Python allows dynamic property addition:

s1.course = "Python Programming"
print(s1.course)

But it’s not ideal for structured design — better to define properties in the class.


🔁 Modify Object Properties

s1.age = 22

❌ Delete Object Properties or Entire Object

del s1.age     # Delete property
del s1         # Delete object

🧪 Real-Life Example: Car Class

class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

    def start_engine(self):
        print(f"{self.brand} engine started!")

car1 = Car("Toyota", 2020)
car1.start_engine()

🎯 Output:

Toyota engine started!

📝 Summary – Python Classes & Objects at a Glance

ConceptSyntax / Example
Define a classclass ClassName:
Create objectobj = ClassName()
Constructordef __init__(self, param):
Access propertyobj.name
Call methodobj.method()
Add propertyobj.new_attr = value
Delete propertydel obj.attr

🏁 Final Thoughts

Learning how to use classes and objects in Python is the first step toward writing clean, scalable, and real-world code. Whether you’re building a calculator app or a machine learning model, everything revolves around objects.

Start small, practice class structures, and soon you’ll be thinking in objects like a true Pythonista!


📘 Continue exploring advanced OOP topics at TechTown.in