PythonObject Oriented Programming

Python OOP Masterclass: Classes, Objects & Constructors

TT
TopicTrick
Python OOP Masterclass: Classes, Objects & Constructors

Introduction to OOP

Welcome to the foundation of modern software development: Object-Oriented Programming (OOP). While procedural programming focuses on a sequence of steps or functions, OOP focuses on Objects—entities that combine data (attributes) and behavior (methods).

In this tutorial, we will cover:

  1. The difference between a Class and an Instance.
  2. How to define your first Class in Python.
  3. The power of Constructors (__init__).

What is a Class?

Think of a Class as a blueprint, template, or a prototype. It doesn't "exist" as a piece of data itself, but it defines what its objects will look like and how they will behave.

Example: The Circle Blueprint

Imagine a Circle class. Every circle in the world has:

  • Attributes: Radius, Color, Diameter.
  • Methods: Calculate Area, Calculate Perimeter.

The class defines these properties, but it doesn't represent a specific circle until you create an instance.


What is an Instance (Object)?

An Object is a specific "thing" created from the blueprint. If Circle is the blueprint, then a "Red Circle with a 5cm radius" is the Instance.

Every instance lives in its own place in memory and can have its own unique data while sharing the same structure defined by the class.


Creating a Class in Python

In Python, we use the class keyword. By convention, class names use UpperCamelCase.

python
1class MyClass: 2 """A simple example class""" 3 pass

The Need for Constructors

If we create an empty class, we have to manually assign attributes to every object we create:

python
1class Student: 2 pass 3 4s1 = Student() 5s1.name = "John" 6s1.age = 20 7 8s2 = Student() 9s2.name = "Peter" 10s2.age = 21

This is tedious and error-prone. This is where the Constructor comes in.


The Constructor (__init__)

The __init__ method is a special "dunder" method that runs automatically whenever you create a new object. It's used to initialize the object's attributes.

Parameterized Constructor

This is the most common type, where you pass values to the class when creating an object.

python
1class Student: 2 def __init__(self, name, age): 3 self.name = name # 'self' refers to the specific instance 4 self.age = age 5 6s1 = Student("John", 20) 7s2 = Student("Peter", 21) 8 9print(f"{s1.name} is {s1.age} years old.")

Understanding 'self'

The 'self' parameter is a reference to the current instance of the class. It allows you to access variables that belong to the class from within its methods.


    Python Trick: Multiple Constructors?

    A common question is: Can I have multiple __init__ methods in one class?

    In Python, the answer is No. If you define multiple __init__ methods, Python will only use the last one defined.

    python
    1class X: 2 def __init__(self): 3 print("First") 4 def __init__(self): 5 print("Second") 6 7obj = X() # Output: Second

    Python doesn't support "Constructor Overloading" in the traditional sense (like Java or C++), but you can achieve similar results using default arguments or class methods.


    Conclusion

    You now know the difference between a blueprint (Class) and a real-world entity (Object), and how to use the __init__ method to streamline your code.

    In the next tutorial, we'll dive deeper into Class Variables vs. Instance Variables and explore the different types of methods!

    Keep Practicing!

    Try creating a `Car` class with attributes like `make`, `model`, and `year`. Print out different car objects to see how they differ!