Skip to main content

Classes and Objects in Python

Object-Oriented Programming (OOP) is an amazingly powerful programming paradigm. It allows packaging data (characteristics) and behaviors (actions) together in structures called Classes, and then creating independent "copies" of these structures called Objects.

What is a Class?

Imagine a class like a "mold", a "blueprint", or a "recipe". It defines what characteristics something will have, but it is not that something itself.

In Python, we define a class with the class keyword.

class Dog:
# This is the "constructor" method (runs when creating a new object)
def __init__(self, name, breed, age):
# self.name is an ATTRIBUTE (a characteristic the object stores)
self.name = name
self.breed = breed
self.age = age

# This is a METHOD (an action the object can perform)
def bark(self):
print(f"Woof! I am {self.name}")

def have_birthday(self):
self.age += 1
print(f"Happy birthday {self.name}! You are now {self.age} years old.")

Explaining __init__ and self

  • __init__: Is a special method (the constructor). Python calls it automatically every time you create a new object of that class.
  • self: Is a reference to the exact object being created or used at that moment. It is mandatory as the first parameter in all methods of a class.

What is an Object?

An object is an "instance" (a concrete creation) made from the Class mold. You can create infinite objects from a single class, and each one will store its own independent information.

# Creating "instances" (Objects) of the Dog class
dog1 = Dog("Fido", "Golden Retriever", 3)
dog2 = Dog("Rex", "German Shepherd", 5)

# Accessing Attributes (characteristics)
print(dog1.name) # Output: Fido
print(dog2.breed) # Output: German Shepherd

# Executing Methods (actions)
dog1.bark() # Output: Woof! I am Fido
dog2.have_birthday() # Output: Happy birthday Rex! You are now 6 years old.

Benefits of Classes

  1. Modeling the real world: If you are programming a game, instead of having 50 loose variables, you can have a single Warrior object.
  2. Reusability: You define the code once and use it to create thousands of different objects without repeating logic.