Skip to main content

Command Palette

Search for a command to run...

Class and Objects in Python Review

Updated
2 min read

Perfect timing to review this before Django 👍
Django is very class-heavy, so getting this clear will make everything feel easier.


What is a Class in Python?

A class is a blueprint (template) to create objects.

Think:

  • Class → Design of a house 🏠

  • Object → Actual house built from that design


What is an Object?

An object is an instance of a class.
It holds real data and can use the class’s methods.


Basic Example (Very Important)

class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll

    def info(self):
        print(self.name, self.roll)

Creating Objects

s1 = Student("Aarav", 1)
s2 = Student("Sita", 2)

s1.info()
s2.info()

Output

Aarav 1
Sita 2

Key Terms You MUST Know

1. __init__ (Constructor)

  • Runs automatically when object is created

  • Used to initialize data

def __init__(self):
    pass

2. self

  • Refers to current object

  • Without self, Django will break 😄

❌ Wrong:

name = name

✅ Correct:

self.name = name

Class Variables vs Instance Variables

class College:
    college_name = "ABC College"   # class variable

    def __init__(self, student):
        self.student = student     # instance variable
c1 = College("Ram")
c2 = College("Shyam")

print(c1.college_name)
print(c2.college_name)

Methods in Class

Instance Method

def show(self):
    print(self.name)

Class Method

@classmethod
def college(cls):
    print("ABC College")

Static Method

@staticmethod
def hello():
    print("Hello")

Inheritance (VERY IMPORTANT FOR DJANGO)

class User:
    def login(self):
        print("User logged in")

class Admin(User):
    def delete(self):
        print("Deleted")
a = Admin()
a.login()
a.delete()

➡ Django uses inheritance everywhere (models.Model, views.View)


Encapsulation (Basics)

class Bank:
    def __init__(self, balance):
        self.__balance = balance  # private

    def get_balance(self):
        return self.__balance

Why Classes Matter in Django (BIG PICTURE)

Django PartClass Usage
Modelsclass Product(models.Model)
Viewsclass ProductView(View)
Formsclass ProductForm(forms.ModelForm)
Adminclass ProductAdmin(admin.ModelAdmin)

Django-Style Preview Example

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def discounted_price(self):
        return self.price - 10

➡ This is exactly how Django Models think, just with extra magic.


Quick Practice Tasks (Before Django)

Task 1

Create a class Teacher with:

  • name

  • subject

  • method details()


Task 2

Create a class Car:

  • brand (class variable)

  • model

  • method show()


Task 3 (Django mindset)

Create:

class User:
    username
    email
    method: display()