Call Python function from another Python file
In this article, you will know how to call a function of other Python files using the import keyword. Also, you will get to know how to import a single class, not the whole file.
Building software needs a network of codes and files of codes in a systematic way. The network can be created by calling functions from one file to another.
Python has a simple way to use the functions of other Python files. Importing that file using import keyword and aliasing it is very simple. For example, the same directory has two Python file baseFile.py and callerFile.py having their functions. Then how you can use baseFile.py functions in callerFile.py, that will see in the code below.
def intro(): return 'This is baseFile' def secFun(): return 'This is second function'
import baseFile as b print(b.intro())
This is baseFile
Import only class you want
In some cases, you import the whole file but you need some of the classes functions only. There is no need to import the whole file and just import that specific class only. So if you want to import any specific class then you can follow this way of import.
class First: def firstFun(): return 'This is First class' class Second: def secFun(): return 'This is Second class'
from baseFile import Second as s print(s.secFun())
This is Second class
Import all classes, functions and variables using *
* is a wild card symbol that is used to import all classes, functions and variables present in the python file. In the various field, it is used to search all the content present in the table of file.
from baseFile import * print(Second.secFun())
I hope you got the idea of using functions, functions of a class from other Python files.