How To Import A Class In Python

In this tutorial, we will learn how to import a class in Python. Importing a class means including the functionality of one class into another class, which allows you to reuse existing code and make your program more modular and organized. By the end of this tutorial, you will be able to efficiently import and use classes in your Python projects.

Step 1: Create the Class That You Want to Import

Before you can import a class, you need to have a class to import. For the purpose of this tutorial, let us create a simple class called Person with a few attributes and methods. Save this class in a file called person.py.

Step 2: Import the Class into Another File

Now that we have a class to import, let’s create a new Python file called main.py. In this file, you will import the Person class using the import keyword, followed by the file name without the extension (in this case, person).

To import the class, we use the from <module> import <class> statement, where module. In our case, the module is the file person.py and the class is the Person class.

Step 3: Instantiate and Use the Imported Class

After importing the class, you can now create instances of the Person class and use its methods.

Full Code

For reference, here is the full code for both files.

person.py

main.py

Output

Hello! My name is John Doe and I am 25 years old.
Hello! My name is Carla Smith and I am 35 years old.

Conclusion

This tutorial demonstrated how you can import and utilize classes in Python, making it easy to reuse and organize your code. By importing classes, you can build more complex applications while maintaining clean and maintainable code. Happy coding!