Python Practice › OOP Programs › Program 1

Class with a constructor

EasyOOP Programs · 1 of 48

Write a Python class with a constructor (__init__) that sets the object’s attributes.

Advertisement
Output
Created student Asha
Asha 7

Approach

  1. __init__ runs automatically when an object is created.

Solution

Python
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.

More oop programs

← All 48 OOP Programs

Leave a Comment