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 code.py which consists of a class named CodeSpeeedy. The code present in code.py is shown below.

code.py

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 app.py. In app.py we will be importing CodeSpeedy class using the import keyword. The code in app.py is shown below:

app.py

import code
obj = code.CodeSpeedy()
n=5
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))

Output:

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.