__init__ and self
__init__: setting up a new object
__init__ is a special method that runs automatically when an object is created. It gives the object its starting attributes:
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
asha = Student("Asha", 92)
leo = Student("Leo", 78)
print(asha.name, asha.grade)
print(leo.name, leo.grade)Student("Asha", 92) creates an object, then calls __init__ with name="Asha" and grade=92. Now every student is guaranteed to have both attributes.
What is self?
self is the object itself: the particular student being set up or used. self.name = name means "store this value in this object's name attribute".
When you call a method on an object, Python passes the object as self automatically:
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def describe(self):
return f"{self.name} has {self.grade}%"
asha = Student("Asha", 92)
print(asha.describe()) # Python calls Student.describe(asha)
print(Student.describe(asha)) # exactly the same thingself is just a convention, but it's universal; always call it self.
Defaults and validation
class Product:
def __init__(self, name, price, stock=0):
if price < 0:
raise ValueError("Price can't be negative")
self.name = name
self.price = price
self.stock = stock
lamp = Product("Desk lamp", 27.75)
chair = Product("Chair", 349, stock=8)
print(lamp.name, lamp.stock, chair.stock)
Product("Broken", -5)Checking values in __init__ means a bad object can never exist.
Class attributes: shared by all
An attribute defined directly in the class body is shared by every instance:
class Student:
school = "CodeMIRAI Academy" # class attribute: shared
count = 0
def __init__(self, name):
self.name = name # instance attribute: per object
Student.count += 1
a = Student("Asha")
b = Student("Leo")
print(a.school, b.school)
print(Student.count, "students")Use class attributes for values that are the same for all instances, like constants or counters. Never use a mutable class attribute (a list) to hold per-object data, because every object would share it.