Set_up: I have a .py file for each function I need to use in a program.
In this program, I need to call the function from the external files.
I\'ve tried:
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
First of all you do not need a .py
.
If you have a file a.py
and inside you have some functions:
def b():
# Something
return 1
def c():
# Something
return 2
And you want to import them in z.py
you have to write
from a import b, c
Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method
from anotherfile import method1
if method1 is part of a class, let the class be class1, then
from anotherfile import class1
then create an object of class1, suppose the object name is ob1, then
ob1 = class1()
ob1.method1()
You don't have to add file.py
.
Just keep the file in the same location with the file from where you want to import it. Then just import your functions:
from file import a, b
Inside MathMethod.Py.
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
Inside Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
Output:1200