How to Import a Class from a File in Python [4 ways]

If you are a learner or a developer, you may know how important it is to maintain your code in different modules (Python files), so you can reuse it by importing the classes or module itself.

In this Python article, let me tell you “How to import a class from a file in Python” in multiple ways with some practical and realistic examples.

Python is an object-oriented programming language, so it allows developers to create classes in different modules and we can import those classes into our project (main code) which is a better way to maintain and organize our code. Also, we’ll see how to import classes from different folders.

Different ways to import the class from another file

  • How to import user-defined classes from the module
  • How we can import built-in classes in different ways
  • Import all classes at once
  • Import class from different folder

The process involves two different steps: first you have to create a module or a class in Python and you have to import these classes or modules to another Python file.

Step 1: How to create Module and Classes in Python

Before importing the class from the user-defined module, a Python file should be created by the user into the main program.

One has to create classes in that user-defined module.

Scenario: In the example, I’ve created one Python file(module) called greetings.py and then I’ve created 2 different classes called “Welcome” and “GoodBye”.

# File: greetings.py
class Welcome:
    def greet(self, name):
        return f"Welcome {name} to the Python Guides!"

class GoodBye:
    def farewell(self, name):
        return f"Goodbye, {name}! We hope to see you soon..."

Below is the screenshot of the code execution in the visual studio:

import a class from a file in Python

Step 2: How to import a class from a file in Python

To import the class or modules in Python, we can use the import keyword of Python.

We will see the example, where we will import a class from a file in Python that we’ve made (Welcome and GoodBye) from the module (greetings.py).

from greetings import Welcome, GoodBye

# Creating instances of the classes
welcome_message = Welcome()
goodbye_message = GoodBye()

# User input for name
user_name = input(" Enter your name: ")

# Printing personalized greetings
print(welcome_message.greet(user_name))
print(goodbye_message.farewell(user_name))

Output:

Enter your name: George
Welcome George to the Pyhton Guides!
Goodbye, George! We hope to see you again soon.

After executing the code in the visual studio, The below screenshot is taken:

How to import class in python

How to Import Built-in Classes in Python

In Python, there are lots of pre-defined classes and modules are there who perform different tasks. We will take one example by importing a math module and using its classes in Python.

Also, we will see some different ways to import classes from the built like we will try to import a particular class from the module, and then we will see how to import the module only to access the classes in Python:

# Example 1: Square Root
from math import sqrt
num = 25
sqrt_result = sqrt(num)
print(f"The square root of {num} is: {sqrt_result}")


# Example 2: Power Function
import math

base = 2
exponent = 3
power_result = math.pow(base, exponent)
print(f"{base} raised to the power of {exponent} is: {power_result}")

Output:

The square root of 25 is: 5.0
2 raised to the power of 3 is: 8.0

The screenshot is mentioned below:

 import class from another module in Python

How to import all classes from the module

You can also access all the classes of the module by importing all classes from a file using the ” * ” operator.

Let’s see the example of How to import all classes from a file in Python using * operator.

from math import *

# Example 1: Square Root
num = 25
sqrt_result = sqrt(num)
print(f" The square root of {num} is: {sqrt_result}")

# Example 2: Trigonometric Functions
angle_in_radians = radians(45)
sin_result = sin(angle_in_radians)
cos_result = cos(angle_in_radians)
print(f" The sine of 45 degrees is: {sin_result}")
print(f" The cosine of 45 degrees is: {cos_result}")

# Example 3: Power Function
base = 2
exponent = 3
power_result = pow(base, exponent)
print(f" {base} raised to the power of {exponent} is: {power_result}")

# Example 4: Ceiling and Floor Functions
float_number = 4.75
ceiling_result = ceil( float_number)
floor_result = floor( float_number)
print(f" The ceiling of {float_number} is: {ceiling_result}")
print(f" The floor of {float_number} is: {floor_result}")

Output: Here, I have tried to use different classes from the math module as we can use any of them:

 The square root of 25 is: 5.0
 The sine of 45 degrees is: 0.7071067811865476
 The cosine of 45 degrees is: 0.7071067811865476
 2 raised to the power of 3 is: 8.0
 The ceiling of 4.75 is: 5
 The floor of 4.75 is: 4

Below I have mentioned the screenshot:

how to import all classes from the file in python

How to Import classes from different folders

In some cases, we need to categorize the modules in different folders. So we can also import the classes from different folders in Python.

Let’s take one example where I will create one module and class in a different folder and import it into my main project code.

How to import class from the different file in python

Now let’s see how we can import these classes into our main project file.

from Calculation.sum import SUM
result = SUM(5,3)

from Calculation.sub import SUB

result = SUB(10, 5)

Output:

Addition is : 8
Substraction is : 5

Here is the screenshot mentioned below:

How to import class from same folder in python

Conclusion

In this tutorial, I’ve explained how to import a class from a file in Python, from user-defined modules and pre-defined modules.

And, I have explained how to import all the classes at once using the ” * ” operator from the module. I have taken some examples of how to import classes from different folders which is important to maintain and organize our code in a good manner.

I hope you understand these methods and will implement them in your code.

You may also like to read: