Python 3 import of classes

Asked

Viewed 5,446 times

1

I have three . py files in my directory: Banco.py, app.py, Usuarios.py.

My app.py contains the Tkinder import that I am using in the code and here I start all my view and in it I import the class Usuarios.py as follows:

#Arquivo app.py
from .Usuarios import *
from tkinter import *

class Application:
def __init__(self, master=None):

In the archive Usuario.py contains all SQL executions for Insert, delete, update and select, and in that file import the file Banco.py, follow:

#Arquivo Usuarios.py
from .Banco import Banco

class Usuarios():
    def __init__(self, idusuario=0, nome="", telefone="", email="", usuario="", senha="" ):

Then in the Bank file just give the import in sqlite for its use, follows:

#Arquivo Banco.py
import sqlite3

class Banco():
    def __init__(self):

The problem arises when running the app.py which returns me the following error error:

/usr/bin/python3.6 "/home/owi/Documents/Pycharmprojects/Tkinder examples/app.py" Traceback (Most recent call last): File "/home/owi/Documents/Pycharmprojects/Tkinder examples/app.py", line 1, in from . Users import * Modulenotfounderror: No module named 'main.Users'; 'main' is not a package

Process finished with Exit code 1

I would like to understand which problem related to the main is not correct since all classes contain def __ini__.

1 answer

2

The ideal is to put everyone in one package.

Structure your project folder like this:

meuprojeto/
    __init__.py            
    app.py                         
    Usuario.py
    Banco.py

Whereas __init__.py is a file with nothing. When a page has a __init__.py, Python knows it’s a package. So you can import libraries like this:

from meuprojeto import Usuarios

Usuarios.funcao()

Or else:

import meuprojeto as mp

mp.Usuarios.funcao()

I don’t like anything to be implied in my programs, so I usually give preference to the second method.

Remembering that the idiomatic way of naming modules in python is by using only minuscule letters, e.g.: usuarios

  • It remained to say that by doing this - of putting the project in a package, the AP syntax, of importing the files prefixing them with a "." will now work.

Browser other questions tagged

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