agyanadda@gmail.com

Python Classes and Objects

Object-Oriented Python 1 min read Updated Dec 4, 2026 Topic 23 of 32

Object-oriented programming (OOP) groups data and the functions that work on it into classes.

  • A class is a blueprint (Student)
  • An object is one thing made from it (asha = Student("Asha"))

init and self

__init__ runs when an object is created and sets its attributes. self is the object itself — the first parameter of every method.

Attributes

  • Instance attributes: self.name — different for each object
  • Class attributes: defined in the class body — shared by all objects

Methods

  • Normal methods use self
  • @classmethod gets the class (cls) — useful for alternative constructors
  • @staticmethod — a helper that needs neither

Properties

@property lets a method be read like an attribute and is used for validation with a setter.

Special (dunder) methods

__str__ (for print), __repr__ (for debugging), __len__, __eq__, __lt__, __add__ — make objects work with built-in operations.

dataclasses

@dataclass writes __init__, __repr__ and __eq__ for you.

Example

Example — A BankAccount class Python
class BankAccount:
    bank_name = "AgyanBank"            # class attribute

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

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

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

    def __str__(self):
        return f"{self.owner}: ₹{self._balance:,.2f}"


asha = BankAccount("Asha", 1000)
ravi = BankAccount("Ravi")
asha.deposit(500).deposit(250)
ravi.deposit(2000)

print(asha)
print(ravi)
print(asha.balance, BankAccount.bank_name)

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

print(Product("Pen", 20))

Output: Asha: ₹1,750.00, Ravi: ₹2,000.00, 1750 AgyanBank, Product(name='Pen', price=20)

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method runs when an object is created?

Exercise 2 True / False

self refers to the current object inside a method.

Exercise 3 Fill in the Blank

Make a method readable like an attribute with the @___ decorator.

Frequently Asked Questions

Not strictly. A single underscore (_balance) means "internal, please don't use it from outside". A double underscore (__balance) renames the attribute to make accidental access harder, but it is still reachable.