Call from parent file in python

I have a main.py file and a file called classes.py

main.py contains the application and what happens, while class.py contains some classes.

main.py has the following code

main.py

import classes

def addItem(text):
    print text

myClass = classes.ExampleClass()

And then we have classes.py

classes.py

class ExampleClass (object):
    def __init__(self):
        addItem('bob')

Surprisingly, it’s not the actual code that I use, because I removed everything that may prevent you from seeing what I want to do. I want to be able to call the method defined in main.py from a class in .py classes. How to do it?

Thank you in advance

+3
source share
4 answers

, Alex Martelli. , , , , , ...

A B, , , , C, C.

+9

. , , main.py, , , main :

class ExampleClass (object):
    def __init__(self):
        import main
        main.addItem('bob')

, , ...

+3

I would suggest placing common functions either in .py classes, or perhaps even better in the third module, perhaps utils.py.

+1
source

All executable code must be inside if __name__ == "__main__". This will prevent its execution when importing as a module. In main.py

if __name__=="__main__":
    myClass = classes.ExampleClass()

However, since dF states are probably better to refactor at this stage than to try to resolve cyclic dependencies.

+1
source

All Articles