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.
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.
- 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/c2refer 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.
| Characteristic | Meaning | Car example |
|---|---|---|
| State | Data stored in attributes | brand = "Toyota", speed = 80 |
| Behaviour | What it can do (methods) | start(), accelerate(20) |
| Identity | Separate existence even if values match | Two 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) | Objects | State | Behaviour |
|---|---|---|---|
| House plan | Your house, neighbour house | rooms, color, area | open_door(), paint() |
| Car | car1 Toyota, car2 Honda | brand, color, speed | start(), brake() |
| Student | Asha, Ravi, Meena | name, roll, marks | study(), write_exam() |
| BankAccount | A001, A002 | number, holder, balance | deposit(), withdraw() |
| Mobile | Your phone, my phone | model, battery | call(), charge() |
| Book | Python book, C book | title, author, price | open(), discount() |
| Cookie cutter | Each cookie | shape, topping | bake(), decorate() |
Differences between class and object
| Point | Class | Object |
|---|---|---|
| Meaning | Blueprint / type | Instance of that type |
| Nature | Logical definition | Runtime value with its own data |
| Created with | class statement (once) | Calling the class: Student() |
| Count | One definition | Any number of instances |
| Example | class Car: | car1, car2 |
| Real life | House drawing | Actual houses |
Syntax of a class
- Minimum form:
class Name:plus an indented body. Usepassif 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).
| Part | Example | Purpose |
|---|---|---|
| Header | class Student: | Declare a new type |
| Docstring | """A learner.""" | Describe the class |
| Class attribute | school = "ABC" | Shared data for all instances |
__init__ | def __init__(self, name): | Initialize a new object |
| Instance method | def show(self): | Behaviour on one object |
| Class method | @classmethod | Behaviour on the class |
| Static method | @staticmethod | Utility 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)callsStudent.__init__and binds the new object to the names.- Attributes assigned on
selfinside__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 = amakes 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
| Point | Instance attribute | Class attribute |
|---|---|---|
| Where set | Usually on self in __init__ | Directly in the class body |
| Copies | One per object | One shared value on the class |
| Access | obj.name | Class.name or obj.name (lookup) |
| Typical use | Per-object state | Defaults, counters, constants |
| Example | self.balance | BankAccount.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 asself. s.greet()is equivalent toStudent.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 createobj.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)) Advanced — Classes & Objects
Attribute lookup order (simplified)
- Reading
obj.attrlooks first on the instance__dict__, then on the class, then on base classes (MRO). - Writing
obj.attr = valuenormally stores an instance attribute, even if a class attribute with the same name exists. - That is why assigning
v.count = 10on a Visitor instance can shadow the shared classcountfor 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)orobj.__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 / call | Role |
|---|---|
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) 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'>.
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()) 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 = aaliases; use acopy()method orcopy.copywhen you need independence.- Use
isinstancefor type checks that should allow subclasses. - Add a clear
__str__early soprint(obj)is readable while learning. - Keep one responsibility per class: a
Studentshould 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.
Practice Programs List
- Create a
Carclass with brand, color, and speed plusstart,accelerate, andbrake. Make three cars. - Build a
Studentlist, print each grade, and find the class average and topper. - Model
BankAccountso withdraw refuses overdrafts and prints a clear message. - Write
Bookwithdiscounted_price(percent)and a custom__str__. - Demonstrate aliasing (
b = a) then write acopymethod that returns a new object. - Add a class-level counter that tracks how many objects were created.
- Write
Pointwithdistance_to(other)and test three points. - Use
getattr/setattrto read and add an attribute dynamically, then redo it with normal access. - Create five real-life class/object pairs from college or work and implement one fully.
- Show
isvs==for two objects with equal field values (before defining__eq__). - Pass an object into a function that changes an attribute; print before and after.
- Build a tiny inventory of
Productobjects and print those under a price limit.