Classes & __init__

Classes & __init__ in Python: Imagine you are an architect. You create a single "Blueprint" for a house.

Concept Explanation

Imagine you are an architect. You create a single "Blueprint" for a house. This blueprint isn't a house itself—you can't sleep in it—but it defines exactly what a house should look like: how many windows it has, the color of the roof, and the size of the kitchen. From that one blueprint, you can build 100 actual houses.

In Python, a Class is that blueprint. An Object is the real house built from it. This style of programming is called Object-Oriented Programming (OOP), and it's the standard for building complex software like video games, social networks, and AI systems.


Syntax or Core Structure

The class keyword and __init__

The __init__ method is the "constructor." It runs automatically every time you create a new object from your class. Its job is to set up the initial data for that object.

class Dog:
    # The Constructor
    def __init__(self, name, breed):
        self.name = name   # Attribute
        self.breed = breed # Attribute

# Creating an Object (Instantiating)
my_dog = Dog("Buddy", "Golden Retriever")

print(f"My dog's name is {my_dog.name}")

Code Example #1 (Basic)

Using a class to manage a simple inventory item.

class Product:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.stock = quantity

# Creating different products from the same blueprint
p1 = Product("Laptop", 1200, 10)
p2 = Product("Mouse", 25, 50)

print(f"Item 1: {p1.name} - ${p1.price}")
print(f"Item 2: {p2.name} - ${p2.price}")

Code Example #2 (Intermediate)

Adding complexity with multiple attributes and dynamic initial values.

class Smartphone:
    def __init__(self, brand, model, storage_gb=128):
        self.brand = brand
        self.model = model
        self.storage = storage_gb
        self.battery_level = 100 # Default starting value
        self.is_powered_on = False

phone1 = Smartphone("Apple", "iPhone 15", 256)
phone2 = Smartphone("Samsung", "Galaxy S23") # Uses default 128GB

print(f"{phone1.brand} {phone1.model} has {phone1.storage}GB")
print(f"{phone2.brand} storage: {phone2.storage}GB")

Real World Example

Imagine you are building a Role-Playing Game (RPG). You need a way to track hundreds of different enemies.

# 🎮 RPG Game Engine Fragment
class Enemy:
    def __init__(self, type, health, power):
        self.type = type
        self.hp = health
        self.damage = power
        print(f"A wild {self.type} appeared!")

# Spawning enemies
goblin = Enemy("Goblin", 50, 5)
dragon = Enemy("Red Dragon", 1000, 150)

print(f"The {dragon.type} has {dragon.hp} HP remaining.")

Common Mistakes

  1. Forgetting self: This is the #1 mistake. Every method inside a class (including __init__) MUST take self as its first parameter. self represents the specific object you are working with.
  2. Missing Parentheses: You define a class with class MyClass:, but you create an object with obj = MyClass(). If you forget the (), you are referencing the blueprint itself, not building a house!
  3. Indentation Errors: Just like functions and loops, everything belonging to a class must be indented inside the class block.

Best Practices

  • Capitalize Class Names: By convention (PEP 8), class names should use PascalCase (e.g., UserAccount), while variables and functions use snake_case.
  • Keep it Descriptive: Your attributes names should describe the data they hold. self.hp is okay, but self.health_points is clearer.

Practice Exercises

  1. The Book Class: Create a class Book that takes title, author, and pages in the __init__ method. Create two book objects and print their titles.
  2. The Employee: Create an Employee class with name and salary. In the __init__, add 10% to the salary as a signing bonus automatically.
  3. The Car Maker: Create a Car class with make, model, and year. Create three different cars and store them in a list.