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

Asked

Viewed 1,874 times

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/
  • Novafolder/classes

In the first folder there is a file:

  • Novapasta/main.py

In the second folder, there are two files:

  • New folder/classes/classPrint.py
  • New folder/classes/classGerar.py

The logic is as follows:

  1. I open the main.
  2. The main one matters the class classPrint
  3. The class classPrint matters of class classGerar

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 cannot import the Gerar class. Both classes are in the same folder. But, one cannot import the other.

Obs: If I put main.py in the same class folder. Main works correctly.

Someone has faced this problem and knows the solution?

  • For now, I’ll leave everything in the same folder and create a main shortcut. I wanted to solve this problem to have more code organization. But this bone is.

2 answers

1

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

from classPrint import printar

This will identify to Python that the classes directory has a module structure and then you can use the from classes import classPrint within "main.py".

  • I tried: Modulenotfounderror: No module named 'classPrint'

  • The __init__.py file is inside the directory "classes"?

  • I solved the problem.

  • 1

    It’s nice to say that the __init__.py only required until Python 3.4

1


The solution is as follows:

  1. create a folder called pasteGenerate and put classGerar.py inside hers.
  2. in the file classPrint swap the first line with: "from . pastureGerar import classGerar"

This blessed . before the pastureGerar makes a lot of difference. I just don’t I understand why I can’t put all these classes in the same briefcase.

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

You don’t even need to create a subfolder for the Generator class. Just change this line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.