Mher Harutyunyan
Mher Harutyunyan

Reputation: 183

How to call functions from another file in python

I am not too far into python yet and here is the case.

Say I have one python file called functions.py which holds a class with my functions. Below is an example.

import json

class Functionalities:
    def addelement(element):
        # code goes here`

And I have another python file, kind of 'executable' script which does all the job using functions from functions.py class

Adding from . import functions doesn't help.

How to I call functions from the class from another file?

Upvotes: 2

Views: 10213

Answers (1)

nosklo
nosklo

Reputation: 222862

Unlike java, you don't have to use classes in python. If a class is used only as a holder for functions, chances are that you want a free function (one without a class) instead.

But to answer your actual question, you can use the import statement. That will run the other .py file, and make the namespace available so you can call things defined there.

functions.py:

import json

class Functionalities:
    def addelement(element):
        # code goes here`

main.py:

import functions
f = functions.Functionalities()
f.addelement('some element')

Upvotes: 6

Related Questions