How to import class from another Python file ?

Hello folks, today we are going to learn how to import a class from another Python file.

By importing the classes from other Python files we can use its methods. We import classes and functions from other python files using the keyword import. Let’s look into in detail

Import Class from another Python file using import keyword

Let us consider a Python file named which consists of a class named CodeSpeeedy. The code present in is shown below.

class CodeSpeedy:
  def square(self,n):
    return n**2
  def cube(self,n):
    return n**3
  def power4(self,n):
    return n**4

Our goal in this tutorial is to use this class from another Python file. Let us consider another Python file In we will be importing CodeSpeedy class using the import keyword. The code in is shown below:

import code
obj = code.CodeSpeedy()
print("square of n is" ,obj.square(n))
print("cube of n is" ,obj.cube(n))
print("4th power of n is" ,obj.power4(n))


square of n is 25
cube of n is 125
4th power of n is 625

After importing the class, we declared an object for it. Using that object we called the methods.

Learn more about classes and objects here

Python documentation about classes : here

Learn more about

Leave a Reply

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