Problem when importing a class from another folder and using it. (Python)

0

I'm going crazy here. I'm facing a problem that should have been solved by logic already. The problem is this:

I have two folders:

  • novapasta /
  • novapasta / classes

In the first folder there is a file:

  • novapasta / main.py

In the second folder, there are two files:

  • novapasta / classes / classPrint.py
  • novapasta / classes / classGerar.py

The logic is as follows:

  • I open the main.
  • Main imports class classPrint
  • class classPrint imports class classGenerate
  • So far so good. In the main.py file is the following:

        from classes import classPrint
        objeto = classPrint.printar()
        print(objeto.b)
    

    In the classPrint file is this code:

        import classGerar
        objeto = classGerar.Gerar()
        class printar():
            b = objeto.a
    

    The problem is that classPrint can not import the classGerate. Both classes are in the same folder. But one can not import the other.

    obs: If I put main.py in the same class folder. A main works correctly.

    Has anyone ever faced this problem and knows the solution?

        
    asked by anonymous 16.07.2018 / 00:31

    2 answers

    1
      

    The solution is as follows:

         
  • create a folder called the Generate folder and put the classGerrar.py inside   her.
  •   
  • in the classPrint file change the first line to: "from .pastaGerar   import classGerate "
  •   

    That blessed one. before theGerar folder makes a lot of difference. I just do not   I understand why I can not put these classes all in the same   folder.

    I found a better solution. Go in classPrint.py and replace "import classGerar "by" from. import classGerate "

    You do not even have to create a subfolder for the classGenerate. Just change that line.

        
    16.07.2018 / 02:41
    1

    Within the classes directory create a file named "__init__.py" with the following content:

    from classPrint import printar
    

    This will tell Python that the classes directory has a bunch of modules and then you can use from classes import classPrint inside "main.py".

        
    16.07.2018 / 01:33