Create Class & Object in Python

__init__ runs when you call Student(...). display_info is just a function with self already filled in.

BeginnerObject-Oriented ProgramsExample 1 of 25
create-class-object.py
1# Program to create a simple class and object
2
3class Student:
4 def __init__(self, name, roll_no):
5 self.name = name
6 self.roll_no = roll_no
7
8 def display_info(self):
9 print(f"Name: {self.name}, Roll No: {self.roll_no}")
10
11student1 = Student("Alice", 101)
12student1.display_info()

Output

Name: Alice, Roll No: 101

What's going on

Student("Alice", 101) calls __init__. self.name sticks on that object, not on the class.

student1.display_info() is display_info(student1) with nicer spelling. Forget self in the method signature and Python yells about missing arguments.

No new keyword. That trips people coming from Java.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.