Python Learning Series · @onlysamarrr · Day 30 / 30

Day 30: OOP: Classes and Objects

Day 30 introduces OOP. A class is a blueprint and an object is a real thing made from it. __init__ is the constructor that runs when an object is created, and self is the object the method was called on.

Phase: Intermediate · Reels: 146/450 – 150/450

Quick Answer

Day 30 introduces OOP. A class is a blueprint and an object is a real thing made from it. __init__ is the constructor that runs when an object is created, and self is the object the method was called on.

What You Will Learn

Code

class BankAccount:
    bank = "SBI"

    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

    def deposit(self, amt):
        if amt <= 0:
            raise ValueError("Amount must be > 0")
        self._balance += amt

    @property
    def balance(self):
        return self._balance

acc = BankAccount("Arhan")
acc.deposit(500)
print(acc.balance, acc.bank)
print(acc.owner)

Output

500 SBI
Arhan

Code Explained, Line by Line

  1. class BankAccount: defines a blueprint. bank is a class variable, shared by all accounts.
  2. __init__(self, owner, balance=0) runs when a new account is created and sets owner and balance.
  3. self is the object the method was called on. Forgetting self in a method raises a TypeError.
  4. deposit() increases the balance and raises ValueError for a zero or negative amount.
  5. @property balance lets balance be read like an attribute, but not set directly (a read-only getter).
  6. The four pillars of OOP are Encapsulation, Abstraction, Inheritance and Polymorphism, which come in the following days.
Common Mistake: Forgetting self in a method raises TypeError: takes 0 positional arguments but 1 was given. The first parameter of every method is self.

Real-Life Use

Bank accounts, users, orders and products in real apps are all classes with objects.

Practice Task: Build a Car class: take brand and model in __init__, and add a method that prints the car's introduction.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. What is a class?

Q2. What does __init__ do?

Q3. What happens if a method forgets self?

Today's 5 Reels (from the 90-Day Plan Excel)

146/450ConceptClass = blueprint
147/450Live demoPehli class banao
148/450Common mistakeself bhoolna
149/450QuizQuiz: Car class
150/450Interview / real lifeReal life: OOP kahan use hota
← Day 29← Python Section