🐍 Python📅 Day 10

Class & Object in Python

Define classes, create objects, use __init__, self and instance methods — the entry to OOP in Python.

🎯

Learning objectives

  • Define a class with __init__ and methods
  • Create objects and access their attributes
  • Understand self and the difference between instance and class attributes

💡 Key points

  • class Name: defines a blueprint. Objects (instances) are created by calling Name(...).
  • __init__ is the constructor — runs automatically when the object is created.
  • self refers to the current object; it MUST be the first parameter of instance methods.
  • Attributes defined inside __init__ are per-object. Attributes defined at class level are shared.

💻 Code examples(4)

#1Define a class
python
class Student:
    def __init__(self, name, roll, marks):
        self.name = name
        self.roll = roll
        self.marks = marks

    def print_report(self):
        print(f"{self.roll} {self.name} → {self.marks}")
self is Python's way of saying 'this object'. It's not a keyword — just a convention (but always name it self).
#2Create and use objects
python
s1 = Student("Amit",  1, 87.5)
s2 = Student("Priya", 2, 92.0)

s1.print_report()
s2.print_report()
print(s1.name)         # Amit
Output
1 Amit → 87.5
2 Priya → 92.0
Amit
No `new` keyword — just call the class like a function. Access attributes with a dot.
#3Class vs instance attributes
python
class Counter:
    count = 0                # class attribute — shared
    def __init__(self, name):
        self.name = name     # instance attribute — per object
        Counter.count += 1

a = Counter("A")
b = Counter("B")
print(Counter.count)         # 2  (shared)
print(a.name, b.name)        # A B (per object)
Class attributes live once on the class. Instance attributes live on each object.
#4__str__ for readable printing
python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

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

p = Point(3, 4)
print(p)                # Point(3, 4)  — thanks to __str__
Dunder (double-underscore) methods hook into built-in operations. __str__ controls what print() shows.

🎯 Practice

Q1. What does self represent inside a method?+

The current instance of the class — the specific object that the method was called on.

Q2. What happens if you forget self as the first parameter?+

Calling the method on an instance passes the instance as the first argument. Missing self shifts everything: you get a TypeError or unexpected values.

Q3. Define a class Rectangle with width, height, and an area() method.+

class Rectangle: def __init__(self, w, h): self.width = w self.height = h def area(self): return self.width * self.height

📝 Notes

The 4 pillars of OOP (preview)

| Pillar | One-line meaning | |---|---| | Encapsulation | Bundle data + methods; hint privacy with a leading _ | | Inheritance | class Dog(Animal): — Dog reuses Animal's members | | Polymorphism | Same method behaves differently for different types | | Abstraction | Expose what an object does, hide how |

Today is the foundation — every big Python program (Django, Pandas, PyTorch) is built from classes.

Common beginner mistake

class Timer:
    def start():           # ❌ missing self
        print("started")

t = Timer()
t.start()                  # TypeError: start() takes 0 positional arguments but 1 was given

Always: def start(self): — even if you don't use self inside.