How to import a class from another file in Python

In this tutorial, you will learn how you can import one class of python program to another file of python program.

In python programming you can use import keyword to make class in one file available in another. Importing class from another file using import keyword allowing you to reuse code while keeping your project maintainable.

Import a class from another file in python

Let suppose you have two file called student.py and main.py in directory and you want to reuse the student.py class in main.py then you can do this with the help of import keyword.

class Student:
	def init(self, name, roll_no):
		self.name=name
		self.roll_no=roll_no
	def get_detail(self):
		details=self.name + ‘ ’ + str(self.roll_no)

now let use the student class in main.py

from student import Student
stud_detail =Student(“roy”, 71)
print(stud_detail.get_detail)

Output is:

roy 71

Was this article helpful?
YesNo

1 thought on “How to import a class from another file in Python”

Leave a Comment