⚡0 XP🔥0

Classes and Objects (OOP Basics)

Lesson 26 of 33 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Object-oriented programming in Python - classes, objects, the __init__ constructor, self, instance and class attributes, methods, and modelling real-world things.

What is Object-Oriented Programming?#

So far you've written programs as a series of functions working on data. Object-Oriented Programming (OOP) organises code around objects - bundles that contain both data (attributes) and behaviour (methods).

Real-world example - a car:

  • Attributes (data): brand, colour, speed, fuel
  • Methods (behaviour): start(), accelerate(), brake()

OOP is used in almost every large Python project - Django models, game characters, GUI windows, bank accounts, etc.

Class and object#

  • A class is a blueprint (design / template).
  • An object is an instance made from that blueprint.

One class Car → many objects: my_car, your_car, taxi.

हिंदी में समझें

Class = नक्शा (blueprint), Object = उस नक्शे से बनी असली चीज़।

जैसे एक मकान का नक्शा (class) एक बार बनता है, लेकिन उससे कई मकान (objects) बनाए जा सकते हैं। हर मकान का रंग, मालिक, पता अलग हो सकता है (attributes), लेकिन ढाँचा एक जैसा होता है।

Python में: class Student: नक्शा है, और s1 = Student("Asha"), s2 = Student("Ravi") उस नक्शे से बने दो अलग-अलग students (objects) हैं।

Defining a class#

▶ Try it YourselfPython
Ctrl + Enter to run

Class names use CamelCase by convention: Student, BankAccount, ShoppingCart.

The constructor: __init__#

__init__ is a special method that runs automatically when an object is created. Use it to set the starting attributes:

▶ Try it YourselfPython
Ctrl + Enter to run

Understanding self#

self is the object itself. When you write s1.method(), Python actually calls Student.method(s1) - so inside the method, self is s1.

  • self.name = name means "store name in this object".
  • Every instance method must have self as its first parameter (you don't pass it - Python does).
हिंदी में समझें

self का मतलब है "यह वाला object"।

जब आप s1 = Student("Asha", "Python") लिखते हैं, तो __init__ के अंदर self का मतलब s1 होता है। इसलिए self.name = name का अर्थ है "Asha नाम को इस object (s1) के अंदर रख दो।" जब s2 बनता है, तब self का मतलब s2 होता है।

इसी वजह से हर object अपना अलग data रखता है। self method की पहली parameter होती है, पर call करते समय आपको उसे pass नहीं करना पड़ता - Python खुद करता है।

Methods - functions inside a class#

▶ Try it YourselfPython
Ctrl + Enter to run

Methods can call other methods of the same object using self.method().

Instance attributes vs class attributes#

  • Instance attributes (self.x = ... in methods) - separate for each object.
  • Class attributes (defined directly in the class body) - shared by all objects.
▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

Never use a mutable class attribute (like a list) for per-object data:

class Cart:
    items = []        # shared by ALL carts - a common bug

Create it in __init__ instead: self.items = [].

Changing and checking attributes#

asha.name = "Asha Verma"          # update
asha.city = "Indore"              # add a new attribute (allowed, but better in __init__)
print(hasattr(asha, "city"))      # True
print(getattr(asha, "phone", "N/A"))
print(vars(asha))                 # all instance attributes as a dict

A complete example: shopping cart#

▶ Try it YourselfPython
Ctrl + Enter to run

Why use OOP?#

Benefit Meaning
Organisation data and the functions that use it live together
Reusability create many objects from one class; extend classes (inheritance - next lesson)
Modelling code mirrors real things: Student, Invoice, Product
Maintenance change the class once, every object benefits

Summary#

  • A class is a blueprint; an object is an instance: obj = ClassName(args).
  • __init__(self, ...) sets up each new object; self is the current object.
  • Instance attributes (self.x) are per-object; class attributes are shared.
  • Methods are functions inside a class and always take self first.
  • Create mutable attributes (lists, dicts) inside __init__.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Rectangle class

Create a class Rectangle with:

  • __init__(self, width, height) storing both values
  • area() returning width × height
  • perimeter() returning 2 × (width + height)
2

Bank account

Create a class BankAccount with:

  • __init__(self, owner, balance=0)
  • deposit(amount) - adds to the balance and returns the new balance
  • withdraw(amount) - if amount > balance, return the string "Insufficient funds" (balance unchanged); otherwise subtract and return the new balance
3

Count objects

Create a class Student with a class attribute count = 0. Each time a Student(name) is created, store the name and increase Student.count by 1.

Quick Quiz

Q1.

What is the relationship between a class and an object?

Q2.

When is __init__ called?

Q3.

What does self refer to inside a method?

Q4.

Given class Dog: with species = "Canine" at class level, what is species?

Q5.

What is wrong here?

class A:
    def show():
        print("hi")
A().show()