
Python
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.
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...>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 oldAn 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: TrueEvery 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 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 methodThe `__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())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: 22class 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())| Concept | Remember |
|---|---|
| Class | A blueprint or template for creating objects |
| Object | A specific instance created from a class |
| Instantiation | Creating a new object from a class using class_name() |
| Attribute | A variable that belongs to an object (object.attribute) |
| Method | A function that belongs to an object (object.method()) |
| self | Represents the object itself inside a method |
| __init__ | Constructor method that runs when an object is created |
| Dot Notation | Access attributes and methods using object.name |
Now that you understand the basics of classes and objects, let's learn about methods and how `self` works in more detail.
Ready to practice? Try challenges or explore more concepts
Resources
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