Skip to content

Python import class from another file

  • by

You can use an import statement to import the class from another file in Python. And if you want to access the class method, create an object and use a dot to access the method. The outside method can direct access using a module with a dot.

from folder.file import Klasa
from fileName import className


from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

The import statement consists of the import keyword alongside the module’s name. Use prefix the module name with a . if not using a subdirectory.

Python import class from another file example

Simple example code Importing class from another file.

class File:

# methods
def add(self, a, b):
return a + b

def sub(self, a, b):
return a - b

# explicit function
def msg():
print("Hello File class")

import FileModule

# Created a class object
object = FileModule.File()

# Calling and printing class methods
print(object.add(15, 5))
print(object.sub(15, 5))

# Calling the function


Python import class from another file

Another example

Imagine we have to follow the directory structure:


The file contains a class as shown below:

class Animal:

    def print_animal(self):
        return 'This is an animal class'

Now use this class inside the file

From animal_def import Animal

The complete code inside the will look something like this:
# import Animal class
from animal_def import Animal

# create object of class
animal = Animal()

# call class method

Output: This is an animal class

Do comment if you have any doubts or suggestions on this Python import topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *