foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Understand the concept of classes and objects
  • Create and instantiate classes
  • Work with instance variables and methods
  • Understand the difference between class and instance

Classes and Objects

Imagine you're a car manufacturer. You don't build each car from scratch every time – you have a blueprint that defines what every car should look like and how it should work. Then you use that blueprint to create actual cars.

In programming, a class is like that blueprint, and an object is like an actual car built from the blueprint. Object-Oriented Programming (OOP) is one of the most powerful ways to organize and think about code.


What is a Class?

A class is a blueprint or template that defines:

  • What properties (attributes) objects will have
  • What behaviors (methods) objects can perform
  • How objects are created and initialized

Think of a class as a cookie cutter – it defines the shape, but you can make many cookies from it.

# A simple class definition
class Dog:
    """A blueprint for creating dog objects."""
    pass  # We'll add more later

Creating Objects (Instances)

Once you have a class, you can create objects (also called instances) from it:

# Creating objects from the Dog class
dog1 = Dog()  # First dog object
dog2 = Dog()  # Second dog object
dog3 = Dog()  # Third dog object

print(type(dog1))  # <class '__main__.Dog'>
print(dog1 is dog2)  # False - they are different objects

Each object is a separate entity, even though they come from the same blueprint.


The init Method (Constructor)

The __init__ method is like the "birth" of an object. It runs automatically when you create a new instance and sets up the object's initial state.

class Dog:
    def __init__(self, name, breed, age):
        """Initialize a new dog with its characteristics."""
        self.name = name      # Instance variable
        self.breed = breed    # Instance variable
        self.age = age        # Instance variable

The self Parameter

self refers to the specific object being created. It's like saying "this particular dog":

# Creating dogs with different characteristics
buddy = Dog("Buddy", "Golden Retriever", 3)
max = Dog("Max", "German Shepherd", 5)
luna = Dog("Luna", "Border Collie", 2)

print(buddy.name)   # "Buddy"
print(max.breed)    # "German Shepherd"
print(luna.age)     # 2

Instance Methods

Methods are functions that belong to objects. They can access and modify the object's data:

class Dog:
    def __init__(self, name, breed, age):
        self.name = name
        self.breed = breed
        self.age = age
    
    def bark(self):
        """Make the dog bark."""
        return f"{self.name} says: Woof!"
    
    def celebrate_birthday(self):
        """Increase the dog's age by 1."""
        self.age += 1
        return f"Happy birthday {self.name}! Now {self.age} years old."
    
    def get_info(self):
        """Return information about the dog."""
        return f"{self.name} is a {self.age}-year-old {self.breed}"

Using Methods

buddy = Dog("Buddy", "Golden Retriever", 3)

print(buddy.bark())                    # "Buddy says: Woof!"
print(buddy.celebrate_birthday())      # "Happy birthday Buddy! Now 4 years old."
print(buddy.get_info())                # "Buddy is a 4-year-old Golden Retriever"

Class Variables vs Instance Variables

Instance Variables

  • Unique to each object
  • Created in __init__
  • Accessed with self.variable_name
class Dog:
    def __init__(self, name):
        self.name = name  # Instance variable - each dog has their own name

Class Variables

  • Shared by all instances of the class
  • Defined outside methods
  • Like "family traits" that all objects inherit
class Dog:
    # Class variable - shared by all dogs
    species = "Canis familiaris"
    total_dogs = 0
    
    def __init__(self, name):
        self.name = name  # Instance variable
        Dog.total_dogs += 1  # Modify class variable

print(Dog.species)        # "Canis familiaris"
print(Dog.total_dogs)     # 0

buddy = Dog("Buddy")
max = Dog("Max")

print(Dog.total_dogs)     # 2 - shared by all instances
print(buddy.species)      # "Canis familiaris" - accessible from instances

Bank Account Example

Let's build a more complex example:

class BankAccount:
    """A simple bank account class."""
    
    # Class variable - same for all accounts
    bank_name = "Python Bank"
    
    def __init__(self, account_holder, initial_balance=0):
        self.account_holder = account_holder
        self.balance = initial_balance
    
    def deposit(self, amount):
        """Add money to the account."""
        if amount > 0:
            self.balance += amount
            return f"Deposited ${amount}. New balance: ${self.balance}"
        return "Deposit amount must be positive"
    
    def withdraw(self, amount):
        """Remove money from the account."""
        if amount > self.balance:
            return "Insufficient funds"
        if amount > 0:
            self.balance -= amount
            return f"Withdrew ${amount}. New balance: ${self.balance}"
        return "Withdrawal amount must be positive"
    
    def get_balance(self):
        """Return current balance."""
        return f"Account balance: ${self.balance}"

Using the Bank Account

# Create accounts
alice_account = BankAccount("Alice", 1000)
bob_account = BankAccount("Bob", 500)

print(alice_account.deposit(200))      # "Deposited $200. New balance: $1200"
print(bob_account.withdraw(100))       # "Withdrew $100. New balance: $400"
print(alice_account.get_balance())     # "Account balance: $1200"

# Class variable access
print(BankAccount.bank_name)           # "Python Bank"
print(alice_account.bank_name)         # "Python Bank" (from instance too)

Understanding Object Identity

Every object has a unique identity:

account1 = BankAccount("Alice", 100)
account2 = BankAccount("Alice", 100)

print(account1 == account2)  # False - different objects
print(account1 is account2)  # False - different memory locations

# Even with same data, they are different objects
print(id(account1))  # Unique memory address
print(id(account2))  # Different memory address

Key Points to Remember

  • Class = Blueprint for objects that defines structure and behavior
  • Object = Instance of a class, a concrete realization of the blueprint
  • init = Constructor method that initializes object attributes when created
  • self = Reference to current instance, used to access instance variables and methods
  • Instance variables = Unique to each object
  • Class variables = Shared by all instances
  • Methods = Functions that belong to objects and can access and modify object data

Now you know how to create classes and objects! The real power comes when objects can inherit properties from each other. In the next lesson, we'll explore inheritance and polymorphism – how classes can build upon each other like a family tree.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service