Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
Classes & ObjectsMethods & SelfInstance VariablesClass VariablesConstructors & InitializationInheritance BasicsPolymorphismEncapsulationMagic Methods & Dunder
Python/Oop/Classes And Objects

๐Ÿ—๏ธ Classes & Objects โ€” Building Blocks of OOP

Classes and objects are the foundation of Object-Oriented Programming. A class is a blueprint or template for creating objects, while an object is a specific instance created from that blueprint. Think of a class like an architectural design, and objects like actual buildings built from that design.


๐ŸŽฏ What is a Class?

A class is a template that defines the structure and behavior of objects. It specifies what data (attributes) an object should have and what actions (methods) it can perform. Classes help you organize code by grouping related data and functionality together.

# Define a simple class
class Dog:
    # Class definition (blueprint)
    pass

# Create an object from the class
my_dog = Dog()

print(type(my_dog))  # Output: <class '__main__.Dog'>
print(my_dog)        # Output: <__main__.Dog object at 0x...>

๐Ÿ“ฆ Creating a Basic Class

A class definition uses the `class` keyword followed by the class name. Inside the class, you can define attributes and methods. Attributes are variables that store data, and methods are functions that define behavior.

class Person:
    """A simple person class"""

    # This is a class-level docstring

    def __init__(self, name, age):
        # This method runs when creating a new object
        self.name = name  # Attribute
        self.age = age    # Attribute

    def introduce(self):
        # This is a method
        return f"Hi, I'm {self.name} and I'm {self.age} years old"

# Create objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(person1.introduce())  # Output: Hi, I'm Alice and I'm 25 years old
print(person2.introduce())  # Output: Hi, I'm Bob and I'm 30 years old

๐Ÿ”ง Objects and Instances

An object (or instance) is a specific copy of a class. Each object has its own set of attribute values, but they share the same methods. Creating an object from a class is called instantiation.

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

    def describe(self):
        return f"A {self.color} {self.brand}"

# Create multiple objects
car1 = Car("Tesla", "red")
car2 = Car("Toyota", "blue")
car3 = Car("Ford", "green")

# Each object has its own values
print(car1.describe())  # Output: A red Tesla
print(car2.describe())  # Output: A blue Toyota
print(car3.describe())  # Output: A green Ford

# But they're all of the same type
print(type(car1) == type(car2))  # Output: True

๐Ÿ›๏ธ Class Structure and Syntax

Every class has a clear structure: the class name, the class body containing attributes and methods. The `self` parameter represents the object itself and must be the first parameter in any method.

class Student:
    """Represents a student in a school"""

    # Constructor method - runs when object is created
    def __init__(self, student_id, name):
        self.student_id = student_id  # Store data
        self.name = name
        self.grades = []              # Initialize empty list

    # Regular method - performs an action
    def add_grade(self, grade):
        self.grades.append(grade)

    # Another method - retrieves information
    def get_average(self):
        if len(self.grades) == 0:
            return 0
        return sum(self.grades) / len(self.grades)

# Use the class
student = Student(101, "Sarah")
student.add_grade(95)
student.add_grade(87)
student.add_grade(92)

print(f"{student.name}'s average: {student.get_average():.1f}")

๐ŸŽ Attributes and Methods

Attributes are like variables inside an objectโ€”they store data. Methods are like functions inside an objectโ€”they perform actions or retrieve information. You access both using the dot notation (object.attribute or object.method()).

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner      # Attribute
        self.balance = balance  # Attribute

    def deposit(self, amount):  # Method
        self.balance += amount
        return f"Deposited ${amount}. New balance: ${self.balance}"

    def withdraw(self, amount): # Method
        if amount <= self.balance:
            self.balance -= amount
            return f"Withdrew ${amount}. New balance: ${self.balance}"
        else:
            return "Insufficient funds"

    def get_info(self):         # Method
        return f"{self.owner}'s account has ${self.balance}"

# Create and use
account = BankAccount("John", 1000)
print(account.owner)              # Access attribute
print(account.get_info())         # Call method
print(account.deposit(500))       # Call method that changes state
print(account.withdraw(200))      # Call method

๐Ÿ”„ The __init__ Method

The `__init__` method (called "dunder init") is a special constructor method that runs automatically when you create a new object. It's used to initialize the object's attributes with starting values.

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
        self.current_page = 1  # Track where we are

    def read_pages(self, num):
        self.current_page += num
        return f"Read to page {self.current_page}"

    def get_reading_progress(self):
        percentage = (self.current_page / self.pages) * 100
        return f"{percentage:.1f}% complete"

# Create with initialization
book = Book("1984", "George Orwell", 328)
print(f"Reading: {book.title} by {book.author}")
print(book.read_pages(50))
print(book.get_reading_progress())

๐Ÿ“š Real-World Examples

Simple Calculator

class Calculator:
    def __init__(self):
        self.result = 0

    def add(self, x):
        self.result += x
        return self.result

    def subtract(self, x):
        self.result -= x
        return self.result

    def multiply(self, x):
        self.result *= x
        return self.result

    def clear(self):
        self.result = 0
        return "Cleared"

calc = Calculator()
print(calc.add(10))        # Output: 10
print(calc.add(5))         # Output: 15
print(calc.multiply(2))    # Output: 30
print(calc.subtract(8))    # Output: 22

Pet Management System

class Pet:
    def __init__(self, name, species, age):
        self.name = name
        self.species = species
        self.age = age
        self.health = 100

    def feed(self):
        if self.health < 100:
            self.health = min(100, self.health + 20)
        return f"{self.name} is eating. Health: {self.health}"

    def play(self):
        self.health = max(0, self.health - 10)
        return f"{self.name} is playing. Health: {self.health}"

    def get_status(self):
        return f"{self.name} the {self.species} - Age: {self.age}, Health: {self.health}"

pet = Pet("Max", "Dog", 3)
print(pet.get_status())
print(pet.feed())
print(pet.play())
print(pet.get_status())

โœ… Key Takeaways

ConceptRemember
ClassA blueprint or template for creating objects
ObjectA specific instance created from a class
InstantiationCreating a new object from a class using class_name()
AttributeA variable that belongs to an object (object.attribute)
MethodA function that belongs to an object (object.method())
selfRepresents the object itself inside a method
__init__Constructor method that runs when an object is created
Dot NotationAccess attributes and methods using object.name

๐Ÿ”— What's Next?

Now that you understand the basics of classes and objects, let's learn about methods and how `self` works in more detail.

Next: Methods & Self โ†’


Ready to practice? Try challenges or explore more concepts


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep โ€ข Build Real โ€ข Verify Skills โ€ข Launch Forward

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn