Python – Import a class from another File

This Article explains how to import a class from another Python file.

If you’ve been coding in Python for over a week, there’s a 9 out of 10 chance that you’ve already begun importing some libraries into your code to enhance the functionality of your code. Python would not have the world wide recognition it has now, without the existence of these libraries. But what’s the underlying concept here? How do these libraries bring these almost magical functions into your code? And more importantly, can we replicate such a feature?

Background

Before we get to the main point of this article, we’re going to quickly go over a few other things. You can skip ahead if you already know this, but for those who don’t, I highly recommend you read through all of this.

Below is an example of us importing a fairly common library called time. We’re going to use one of it’s many functions called sleep(). The code for it is shown below.

import time

time.sleep(5)

We’re not interested in what this function does, rather we’re going to be focusing on the construction of the above statement. Does it seem familiar? If you’ve done Classes in Python you’ll have noticed that this is exactly how we call methods from classes. To further illustrate me point, here is a small piece of code from our Python classes article.

class Student:
    def __init__(self,name,age):  #Constructor
        self.name = name
        self.age = age

    def checkage(self):  #Defines function
        if self.age < 18:
            print("Underage")
        else:
            print("18 or Above")  

Student1 = Student("Naomi",20)  #Creates object
Student1.checkage()  #Calls function

Do you see how similar the two ways of calling the function are? Well, that’s because both of them are calling from classes. This part is a little complicated because numpy is a module, not a class. Then what’s a module?

A module is a way of storing reusable Python code, containing classes or functions.

The key point to take away here is that a module can have more than just one class or function. At any rate, that’s enough background. If you’re curious about anything discussed above, you can always google it later.


Creating a Module

If you’ve been following this article carefully, you must have arrived at the conclusion that we need to create a module, where we will create the class to be imported. Don’t worry, you can create a module in less than a min. All you need to do is create a Python file and give it a suitable name.

For the rest of this article, we’ve created a python file called module1.py. We’re going to create a class in this, which we will then import for use in our main Python file. You can import module1.py right away, even though it doesn’t have anything in it. Just using the following command.

import module1

Remember to leave out the .py extension.


Creating a Class

We’ll now create a class in the module1.py file. There is no limit to the number of classes you can add, but for the sake of this article, well stick to one. We’ll also through in a bonus function as well (Not everything has to be in a class).

Below we’ve created a class called maths, which is clearly meant to store math related methods. We’ve created two methods, add and sub which will add and subtract two numbers respectively.

class maths:
    def add(self, n1, n2):
        return n1 + n2
    def sub(self, n1, n2):
        return n1 - n2

#Bonus Function       
def display():
    print("Hello World")

Now back to our main Python file.


Importing

It’s now time to import the module and begin trying out our new class and functions.

In order to call a function or class belonging to module1, that function or class must be preceded by the word module1. This helps any name collisions that may occur if there is a pre-existing function or class with the same name.

import module1

# Created a class object
object1 = module1.maths()

# Calling and printing class methods
print(object1.add(3,5))
print(object1.sub(8,2))

# Calling the function
module1.display()

8
6
Hello World

Importing the module as we mentioned earlier will automatically bring over every single class and function in the module into the namespace. If you’re only going to use a single function, you can prevent the namespace from being cluttered by only importing that function. We’ll demonstrate an example below.

from module1 import display

display()

Now you only need to use display() to call the imported function.


Creating Custom Libraries

You wonder, why bother creating our own modules when their are already so many available? The answer is custom libraries.

When you’re coding extensively, you end up having to code similar pieces of code over and over again. Let’s take GUI libraries as an example. To create a GUI, you need to write dozens of lines of code even for the simplest interface. There’s alot of repetition too, as your basically the same functions over and over again. At some point you realize that it would a better idea to create pack this code into a function and save it in a python file. Later when you want to create a GUI, you can simply call that function with a single call.

This approach is (usually) meant to be a personal one. Everyone has their own style and preferences while coding, so that’s why there is not a universal standard. You don’t really have to think about this on a basic level, but it’s something to consider once you’re more experienced.


This marks the end of the Import a class from another Python File Article. Any suggestions or contributions for CodersLegacy are more than welcome. Relevant questions about the article material can be asked in the comments section below.

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments