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
#or 
from fileName import className

Or

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.

FileModule.py

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")

main.py

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
FileModule.msg()

Output:

Python import class from another file

Another example

Imagine we have to follow the directory structure:

Main
  |-- animal_def.py
  |-- file.py

The animal_def.py 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 file.py.

From animal_def import Animal

The complete code inside the file.py will look something like this:

#file.py
# import Animal class
from animal_def import Animal

# create object of class
animal = Animal()

# call class method
print(animal.print_animal())

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading