Python Practice › OOP Programs › Program 1
Class with a constructor
Write a Python class with a constructor (__init__) that sets the object’s attributes.
Output
Created student Asha Asha 7
Approach
__init__runs automatically when an object is created.
Solution
class Student: def __init__(self, name, roll_no): self.name = name self.roll_no = roll_no print(f"Created student {name}") s = Student("Asha", 7)print(s.name, s.roll_no)Output
Created student Asha Asha 7
Line by line
Line 2
self is the new object; name and roll_no come from the call.
Lines 3-4
Assigning to self.<name> stores the values on that object.
Line 7
Calling the class creates the object and runs __init__ with these arguments.
Learn the concept
New to this topic? Read the lesson, then come back.