Solução - Exercício + if __name__ == '__main__'

This commit is contained in:
Luiz Otávio
2022-11-14 09:53:30 -03:00
parent 92078fa670
commit b6bb185969
3 changed files with 55 additions and 0 deletions

14
aula127.json Normal file
View File

@@ -0,0 +1,14 @@
[
{
"nome": "João",
"idade": 33
},
{
"nome": "Helena",
"idade": 21
},
{
"nome": "Joana",
"idade": 11
}
]

View File

@@ -3,3 +3,29 @@
# e depois crie novamente as instâncias
# da classe com os dados salvos
# Faça em arquivos separados.
import json
CAMINHO_ARQUIVO = 'aula127.json'
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
p1 = Pessoa('João', 33)
p2 = Pessoa('Helena', 21)
p3 = Pessoa('Joana', 11)
bd = [vars(p1), p2.__dict__, vars(p3)]
def fazer_dump():
with open(CAMINHO_ARQUIVO, 'w') as arquivo:
print('FAZENDO DUMP')
json.dump(bd, arquivo, ensure_ascii=False, indent=2)
if __name__ == '__main__':
print('ELE É O __main__')
fazer_dump()

15
aula127_b.py Normal file
View File

@@ -0,0 +1,15 @@
import json
from aula127_a import CAMINHO_ARQUIVO, Pessoa, fazer_dump
# fazer_dump()
with open(CAMINHO_ARQUIVO, 'r') as arquivo:
pessoas = json.load(arquivo)
p1 = Pessoa(**pessoas[0])
p2 = Pessoa(**pessoas[1])
p3 = Pessoa(**pessoas[2])
print(p1.nome, p1.idade)
print(p2.nome, p2.idade)
print(p3.nome, p3.idade)