Splitting codes into . py files

Asked

Viewed 694 times

-2

I started programming now, and I started in python, so I started researching more deeply in this language, and I went to see some videos of game programming, in these videos I saw that the game was divided into several parts (such as UI, a chat system in game, the game itself) and wanted to know how to run several files . py as a single code!!

1 answer

2


Using the "import":

You must import the modules using the import. There are several ways to import a module, see below:

import module                              # Importa o módulo com todos os seus dados
import module as otherModuleName           # Importa o módulo e troca o nome dele
from module import *                       # Importa todos os dados do módulo
from module import data1, data2, data3     # Importa dados específicos do módulo
from module import data as otherDataName   # Importa dados específicos e troca o nome deles

What the import makes is run the module (script . py) and import into your program the data of that module (variables, functions and classes). See this example below:

records.py

url = "www.siteExemplo.com"

name = input("Digite seu nome: ")
password = input("Digite sua senha: ")
validateProfile(name,password)  # Função para verificar se os dados estão corretos.

py.

import registra

print("Obrigado %s por se registrar em nosso site!"%registra.name)
print("Você pode fazer login clicando neste link: %s/login"%registra.url)

Note that in this example, the file code records.py is executed normally and its data is passed to the code being executed.

Another important detail that we can note is that we use point (.) to ask for the module data. If you don’t always want to use dots to use the data, you can import it from the module using the asterisk (imports all the data from the module), or by importing specific data. Example:

from registra import *  # Importa todos os dados do módulo

print("Obrigado %s por se registrar em nosso site!"%name)
print("Você pode fazer login clicando neste link: %s/login"%url)

Python packages:

To keep code well organized, you might want to split your modules into packages. Example:

Jogo
Jogo/Jogador/
Jogo/Carro/Itens
Jogo/Cenario/

In Python, you can import modules that are in other directories through packages. The idea of importing is the same one you saw, only before the module name to be imported, you must pass the folder name followed by a dot. Example:

from Jogo.Jogador import Personagem
from Jogo.Carro.Itens import Roda, Volante
from Jogo.Cenario.Arvores import *

To learn more, read the documentation here.

Browser other questions tagged

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