Classes & Objects
Model real things with classes — the foundation Django is built on.
What you will learn
- Define classes with attributes and methods
- Create objects
- Use _init_ and self
Classes and objects
So far our data has been scattered across separate variables. Classes let us bundle related data and actions together to model a real thing — a user, a product, a bank account.
Think of a class as a blueprint (like an architect’s plan for a house), and an object as an actual thing built from that blueprint (a real house). One blueprint, many houses — one User class, many user objects.
A thing built this way has two kinds of parts, and both have simple names:
- An attribute is a piece of data the object holds — a fact about it, like a user’s
nameoremail. - A method is an action the object can do — a function that lives inside the class, like
greet().
Two special words show up in almost every class. __init__ (note the two underscores on each side) is the setup step that runs automatically the moment an object is created — its job is to fill in the starting attributes. And self always means “this particular object”, so self.name reads or sets the name belonging to this object. Do not worry if that feels abstract — the walk-through below shows exactly when each one fires.
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def greet(self):
return f"Hi, I am {self.name}"
asha = User("Asha", "asha@x.com")
print(asha.greet()) # Hi, I am Asha
print(asha.email) # asha@x.comHere is what happens, step by step:
class User:defines the blueprint. Nothing is created yet — it just describes what every User will look like.__init__is the special setup method (the constructor). It runs automatically whenever you create a User, and its job is to store the starting values.- Inside it,
self.name = nameandself.email = emailsave the given values onto this particular object.selfmeans “the object being built right now.” greet(self)is a normal method (an action the object can do). It usesself.nameto read back this object’s own name.asha = User("Asha", "asha@x.com")creates an object from the blueprint — this triggers__init__, filling in name and email. Thenasha.greet()calls its method andasha.emailreads its stored value.
Note: Output: Hi, I am Asha asha@x.com
Note: This is the heart of Django — every database table is written as a class (a model). Master classes here and Django will feel natural.
Q. What does _init_ do in a class?
✍️ Practice
- Create a
Productclass with name and price, and a method that returns a label. - Make two objects from it.
🏠 Homework
- Build a
BankAccountclass with deposit() and withdraw() methods.