2

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?

Mher Harutyunyan
  • 183
  • 3
  • 12
  • possible duplicate of [Call a function from another file in Python Ask Question](https://stackoverflow.com/questions/20309456/call-a-function-from-another-file-in-python) – eyllanesc Apr 19 '18 at 18:28
  • Don't randomly put functions into classes. There is no need to do so unless you're storing state to be passed between them. – Daniel Roseman Apr 19 '18 at 18:30

1 Answers1

6

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')
nosklo
  • 217,122
  • 57
  • 293
  • 297
  • I just thought i'd better sort functions into different classes (or we can say categories in my case) so not to make a mess in future when there will be a lot of functions in one file. But thanks for the answer and suggestion. It worked! – Mher Harutyunyan Apr 19 '18 at 18:38
  • @MherHarutyunyan the pythonic way to sort functions in python is to use modules... not classes. – nosklo Apr 19 '18 at 18:39