Skip to main content

Python OOP

Classes & Objects

Complete lesson for Classes & Objects using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Classes & Objects

Section: Python OOP. Python classes and objects — class as a blueprint, objects as live instances, real-life examples, syntax, attributes, methods, and how names bind to objects.

What is a class?

  • A class is a user-defined type and a blueprint that describes what its objects will store (attributes) and what they can do (methods).
  • Declaring a class does not create any object by itself; it only defines a new type.
  • In Python everything is an object, and classes themselves are objects of type type.
  • Real-life analogy: an architect drawing of a house. It lists rooms and colour, but you cannot live in the drawing.
class Car:
    """Blueprint for car objects."""

    def start(self):
        print(self.brand, "started")

    def accelerate(self, by):
        self.speed += by
        print(self.brand, "speed =", self.speed)

Class & object — real-life blueprint vs real things

A class is the blueprint (house plan, car design, cookie cutter, admission form); an object is the real thing built from it, each with its own values. The poster links four real-life examples to Python code (Car("Toyota", 120)) and a class vs object table.

Python class and object infographic with real-life examples: a house blueprint creating three houses, a Car class creating Toyota, Honda, and Tata cars, a cookie cutter and cookies, a Student form and three student cards, Python code creating c1 and c2 Car objects, and a class vs object comparison table.
Python class & object — the class says what it is; each object is a real instance with its own values
  • Class: declared once with class — the blueprint / type.
  • Object: created by calling the class — c1 = Car("Toyota", 120).
  • Many from one: one class, any number of instances, each with its own attributes.
  • Names bind to objects: variables like c1 / c2 refer to separate instances.

What is an object?

  • An object (instance) is a live value created from a class. Calling the class like a function creates it: Car().
  • One class can create any number of objects; each keeps its own instance attributes.
  • Real-life analogy: the actual houses built from one drawing. Each has its own address and colour.
CharacteristicMeaningCar example
StateData stored in attributesbrand = "Toyota", speed = 80
BehaviourWhat it can do (methods)start(), accelerate(20)
IdentitySeparate existence even if values matchTwo red Toyotas are still two objects
class Car:
    def start(self):
        print(self.brand, "started")

    def accelerate(self, by):
        self.speed += by
        print(self.brand, "speed =", self.speed)

car1 = Car()
car1.brand = "Toyota"
car1.color = "Red"
car1.speed = 0

car2 = Car()
car2.brand = "Honda"
car2.color = "Blue"
car2.speed = 0

car1.start()
car2.accelerate(40)
print("car1 speed =", car1.speed)

Real-life examples of classes and objects

Class (blueprint)ObjectsStateBehaviour
House planYour house, neighbour houserooms, color, areaopen_door(), paint()
Carcar1 Toyota, car2 Hondabrand, color, speedstart(), brake()
StudentAsha, Ravi, Meenaname, roll, marksstudy(), write_exam()
BankAccountA001, A002number, holder, balancedeposit(), withdraw()
MobileYour phone, my phonemodel, batterycall(), charge()
BookPython book, C booktitle, author, priceopen(), discount()
Cookie cutterEach cookieshape, toppingbake(), decorate()

Differences between class and object

PointClassObject
MeaningBlueprint / typeInstance of that type
NatureLogical definitionRuntime value with its own data
Created withclass statement (once)Calling the class: Student()
CountOne definitionAny number of instances
Exampleclass Car:car1, car2
Real lifeHouse drawingActual houses

Syntax of a class

  • Minimum form: class Name: plus an indented body. Use pass if the body is empty for a moment.
  • By convention class names are CapWords (BankAccount). Methods and attributes use snake_case.
  • The first parameter of an instance method is conventionally named self (the current object).
PartExamplePurpose
Headerclass Student:Declare a new type
Docstring"""A learner."""Describe the class
Class attributeschool = "ABC"Shared data for all instances
__init__def __init__(self, name):Initialize a new object
Instance methoddef show(self):Behaviour on one object
Class method@classmethodBehaviour on the class
Static method@staticmethodUtility without self/cls
class Student:
    """A learner with a name and marks."""
    school = "LearnCodeGuru"

    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def show(self):
        print(self.name, ":", self.marks, "|", Student.school)

s = Student("Asha", 92)
s.show()

Creating objects (instances)

  • s = Student("Asha", 92) calls Student.__init__ and binds the new object to the name s.
  • Attributes assigned on self inside __init__ become that object's instance attributes.
  • You can also attach attributes later (s.city = "Pune"), but prefer setting them in __init__ for clarity.
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, dx, dy):
        self.x += dx
        self.y += dy

p = Point(3, 4)
p.move(1, -2)
print(p.x, p.y)
print(type(p).__name__)
print(isinstance(p, Point))

Names are references (aliasing)

  • Assignment copies the reference, not the object. b = a makes both names refer to the same object.
  • Changing a mutable attribute through one name is visible through the other.
  • To get an independent object, create a new instance (or copy deliberately).
class Box:
    def __init__(self, label):
        self.label = label

a = Box("red")
b = a
b.label = "blue"
print(a.label)

c = Box("blue")
print(a is b)
print(a is c)
print(a.label == c.label)

Instance attributes vs class attributes

PointInstance attributeClass attribute
Where setUsually on self in __init__Directly in the class body
CopiesOne per objectOne shared value on the class
Accessobj.nameClass.name or obj.name (lookup)
Typical usePer-object stateDefaults, counters, constants
Exampleself.balanceBankAccount.bank_name
class Visitor:
    count = 0

    def __init__(self, name):
        self.name = name
        Visitor.count += 1
        self.ticket = Visitor.count

v1 = Visitor("Anu")
v2 = Visitor("Bala")
print(v1.name, "ticket", v1.ticket)
print(v2.name, "ticket", v2.ticket)
print("total =", Visitor.count)

Methods are functions bound to objects

  • Defining def greet(self): inside a class creates a function. Looking it up on an instance binds that instance as self.
  • s.greet() is equivalent to Student.greet(s).
  • Methods can read and change the object's attributes through self.
class Greeter:
    def __init__(self, name):
        self.name = name

    def greet(self, city):
        print(f"Hello {self.name} from {city}")

g = Greeter("Meena")
g.greet("Chennai")
Greeter.greet(g, "Chennai")

Checking types safely

  • type(obj) returns the exact class object used to create obj.
  • isinstance(obj, Class) is preferred for checks; it also respects inheritance.
  • Avoid comparing types with == unless you truly need an exact match.
class Animal:
    pass

class Dog(Animal):
    pass

d = Dog()
print(type(d).__name__)
print(isinstance(d, Dog))
print(isinstance(d, Animal))
print(isinstance(d, object))
L2

Advanced — Classes & Objects

Attribute lookup order (simplified)

  • Reading obj.attr looks first on the instance __dict__, then on the class, then on base classes (MRO).
  • Writing obj.attr = value normally stores an instance attribute, even if a class attribute with the same name exists.
  • That is why assigning v.count = 10 on a Visitor instance can shadow the shared class count for that one object.
class Demo:
    shared = "class-level"

d1 = Demo()
d2 = Demo()
print(d1.shared, d2.shared)

d1.shared = "instance-level"
print(d1.shared)
print(d2.shared)
print(Demo.shared)

__dict__ and dynamic attributes

  • Most user instances keep attributes in a dict-like __dict__.
  • You can inspect vars(obj) or obj.__dict__ while learning; production code usually uses normal attribute access.
  • Classes with __slots__ can skip __dict__ to save memory (covered later).
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

p = Product("Pen", 20)
print(sorted(vars(p).keys()))
print(p.__dict__["name"])

Objects and mutability

  • Whether an object is mutable depends on its type and API, not on "being an object".
  • A custom class instance is usually mutable: you can rebind its attributes.
  • Immutability is a design choice (for example, only setting attributes in __init__ and never changing them).
class Score:
    def __init__(self, value):
        self.value = value

    def bump(self, n):
        self.value += n

s = Score(10)
s.bump(5)
print(s.value)

Useful builtins around classes

Builtin / callRole
type(obj)Exact class of the object
isinstance(obj, T)Type check (includes subclasses)
issubclass(A, B)Whether A inherits from B
getattr(obj, "x", default)Safe attribute read
setattr(obj, "x", v)Dynamic attribute write
hasattr(obj, "x")Whether attribute lookup would succeed
dir(obj)List of reachable names (wide net)
class User:
    def __init__(self, name):
        self.name = name

u = User("Ravi")
print(getattr(u, "name"))
print(getattr(u, "email", "missing"))
setattr(u, "email", "ravi@example.com")
print(hasattr(u, "email"), u.email)

Class as callable factory

  • A class object is callable. Calling it allocates a new instance and runs __init__.
  • You can pass the class around like any other object (callbacks, registries, plugins).
  • Factories sometimes return different subclasses based on input (advanced pattern).
def make_many(cls, n, *args):
    return [cls(*args) for _ in range(n)]

class Token:
    def __init__(self, label):
        self.label = label

tokens = make_many(Token, 3, "ok")
print(len(tokens), tokens[0].label)
L3

Tricky Interview Points

Q1) What is a class in Python?

Answer A class is a blueprint that defines attributes and methods for a new user-defined type. Declaring it does not create instances by itself.

Q2) What is an object (instance)?

Answer An object is a concrete value created by calling a class. It holds its own instance data and can use the class methods.

Q3) How do you create an object?

Answer Call the class like a function: s = Student("Asha", 90). That runs __init__ and returns the new instance.

Q4) Difference between class attribute and instance attribute?

Answer Class attributes are defined on the class and shared (unless shadowed). Instance attributes are usually set on self and belong to one object.

Q5) What does b = a do for two instance variables?

Answer It aliases: both names refer to the same object. Changes through one name are visible through the other.

Q6) Why prefer isinstance over comparing type?

Answer isinstance respects inheritance. type(x) is Animal fails for subclasses that should still count as animals.

Q7) Is everything in Python an object?

Answer Yes. Numbers, strings, functions, classes, and modules are all objects with types and attributes.

Q8) What is PascalCase / CapWords used for?

Answer Class names by PEP 8 convention (BankAccount). Functions and variables use snake_case.

Q9) Can you add attributes after creation?

Answer Yes for normal classes: obj.extra = 1. Prefer defining expected attributes in __init__ for clarity.

Q10) What is the difference between is and == for objects?

Answer is tests identity (same object). == tests equality (values), which you can customize with __eq__.

Q11) Give a real-life class/object pair.

Answer Class BankAccount; objects are each customer account with its own number and balance.

Q12) What does type(obj) return?

Answer The class object used to create that instance, for example <class '__main__.Student'>.

L4

Simple Programs

Student report with multiple objects

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def grade(self):
        if self.marks >= 90:
            return "A"
        if self.marks >= 75:
            return "B"
        if self.marks >= 50:
            return "C"
        return "D"

students = [
    Student("Asha", 92),
    Student("Ravi", 68),
    Student("Meena", 81),
]
for s in students:
    print(f"{s.name}: {s.marks} -> {s.grade()}")
topper = max(students, key=lambda s: s.marks)
print("Topper:", topper.name)

Bank accounts with deposit and withdraw

class BankAccount:
    def __init__(self, number, holder, balance=0):
        self.number = number
        self.holder = holder
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            print("Deposit must be positive")
            return
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient balance for", self.holder)
            return False
        self.balance -= amount
        return True

    def __str__(self):
        return f"{self.number} | {self.holder} | Rs.{self.balance}"

a = BankAccount("A001", "Ravi", 5000)
b = BankAccount("A002", "Priya", 8500)
a.deposit(1500)
b.withdraw(10000)
print(a)
print(b)

Rectangle area and perimeter

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

rects = [Rectangle(4, 5), Rectangle(2.5, 3), Rectangle(10, 1)]
biggest = rects[0]
for r in rects:
    print(f"{r.length} x {r.width} -> area {r.area()}, peri {r.perimeter()}")
    if r.area() > biggest.area():
        biggest = r
print("Largest area =", biggest.area())

Library search over Book objects

class Book:
    def __init__(self, title, author, year):
        self.title = title
        self.author = author
        self.year = year

    def __str__(self):
        return f"{self.title} by {self.author} ({self.year})"

books = [
    Book("Fluent Python", "Ramalho", 2022),
    Book("Python Crash Course", "Matthes", 2019),
    Book("Clean Code", "Martin", 2008),
]
needle = "python"
for b in books:
    if needle in b.title.lower():
        print(b)

Alias vs independent copy

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def copy(self):
        return Point(self.x, self.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

original = Point(1, 2)
alias = original
independent = original.copy()
alias.x = 100
print("original", original)
print("independent", independent)
print("same object?", alias is original)
print("copy same object?", independent is original)

Shopping cart of Product objects

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

class Cart:
    def __init__(self):
        self.items = []

    def add(self, product, qty):
        if qty <= 0:
            raise ValueError("qty must be positive")
        self.items.append((product, qty))

    def total(self):
        return sum(p.price * q for p, q in self.items)

cart = Cart()
cart.add(Product("Pen", 20), 3)
cart.add(Product("Notebook", 55), 2)
print("items =", len(cart.items))
print("total =", cart.total())
L5

Problem Solving Tricks

  • Class = blueprint written once; object = live instance created by calling the class.
  • If you can point at it and it has its own values, think "object"; if it describes many such things, think "class".
  • Name classes CapWords (BankAccount) and methods/attributes snake_case (account_balance).
  • Prefer setting required attributes in __init__ instead of scattering them across the codebase.
  • b = a aliases; use a copy() method or copy.copy when you need independence.
  • Use isinstance for type checks that should allow subclasses.
  • Add a clear __str__ early so print(obj) is readable while learning.
  • Keep one responsibility per class: a Student should not also send email and parse CSV.
  • Class attributes are shared; shadowing them on one instance is a common surprise—know the lookup rules.
  • Pass classes as values when you need pluggable factories.
L6

Practice Programs List

  1. Create a Car class with brand, color, and speed plus start, accelerate, and brake. Make three cars.
  2. Build a Student list, print each grade, and find the class average and topper.
  3. Model BankAccount so withdraw refuses overdrafts and prints a clear message.
  4. Write Book with discounted_price(percent) and a custom __str__.
  5. Demonstrate aliasing (b = a) then write a copy method that returns a new object.
  6. Add a class-level counter that tracks how many objects were created.
  7. Write Point with distance_to(other) and test three points.
  8. Use getattr / setattr to read and add an attribute dynamically, then redo it with normal access.
  9. Create five real-life class/object pairs from college or work and implement one fully.
  10. Show is vs == for two objects with equal field values (before defining __eq__).
  11. Pass an object into a function that changes an attribute; print before and after.
  12. Build a tiny inventory of Product objects and print those under a price limit.