Come on:
You have the class Pessoa
, that means you are a "builder" of people. You can do:
maria = Pessoa()
joao = Pessoa()
dom_pedro_segundo = Pessoa()
So maria
will have all the characteristics (attributes) and actions (methods) that Pessoa
has.
In def __init__(self, nome, idade, comendo=False, falando=False):
you are informing the seguite, "is mandatory in the creation of the Pessoa
that she has a nome
and a idade
whereas comendo
and falando
, in its absence, are attributes (characteristics) False
, thus, in the example above:
maria = Pessoa("Maria", 31)
# A Pessoa acima tem o nome Maria e tem 31 anos de idade, não está falando e nem comendo
joao = Pessoa("João", 15,True)
# A Pessoa acima tem o nome João e tem 15 anos de idade, está comendo mas não está falando
dom_pedro_segundo = Pessoa("Dom Pedro II", 195, falando=True)
# A Pessoa acima tem o nome Dom Pedro II e tem 195 anos de idade, não está comendo mas está falando
Next we have a series of functions (or actions) of Pessoa
in question, she can def falar
and can def parar_falar
, can def comer
and can def parar_comer
, could have others like def andar
, def correr
, def parar
, def dormir
, def acordar
, def pular
... Anything def
is a def
initiating the action that the Pessoa
is able to.
UPDATE
A practical class, besides the person class, would be the User class.
Say you want to make a system where users have registration (so they have an id/email and password), name, date of birth.
If it is a game, you can assign a rank, score, class, nickname, strength, dexterity, intelligence...
If it is a social network, can assign friend list, city, pages that follows, list of posts...
If it is financial (as a personal expense accounting system for the #fikdik family), we can by balance, income, profession.
In the case of financial (personal finance), part of the code (quite simple) would be something like the below, just considering before the classes Gasto
and Ganho
are in the same file, otherwise it would be case to make a
import Gasto
import Ganho
Anyway, the code would be:
class Usuario:
def __init__(self, email, senha, data_nascimento, saldo=0, renda=0, profissao=None):
self.email = email
self.senha = senha
self.data_nascimento = data_nascimento
self.saldo = saldo
self.renda = renda
self.profissao = profissao
self.historico = []
self.logado = False
def aumentar_renda(self):
try:
print("Entre com alguma das opções abaixo")
print("1. Para somar um valor a renda\n2. Para alterar para o valor final da renda")
escolha = int(input("--> "))
if escolha == 1:
valor = input("inseria a somar na renda: ")
self.renda += float(valor)
print(f"O valor adicionado foi {valor} e tua renda agora é {self.renda}!")
elif escolha == 2:
valor = input("Inseria o novo valor da tua renda")
self.renda = float(valor)
print(f"A tua renda agora é {self.renda}!")
else:
print("Escolha uma opção válida!")
except:
print("Escolha uma opção válida!")
def alterar_saldo(self):
print("Escolha uma das opções abaixo")
print("1. Gasto\n2. Ganho")
escolha = int(input("--> "))
if escolha == 1:
gasto = Gasto()
self.historico.append(gasto)
self.saldo -= gasto.valor
elif escolha == 2:
ganho = Ganho()
self.historico.append(ganho)
self.saldo += ganho.valor
else:
print('Escolha uma opção válida!')
class Gasto:
def __init__(self):
self.descricao = input("Insira a descrição do gasto: ")
self.valor = float(input("Insia o valor do gasto: "))
self.local = input("Inseria o local do gasto: ")
def __str__(self):
return f"Descrição do gasto: {self.descricao} \nValor: {self.valor} \nLocal: {self.local}"
class Ganho:
def __init__(self):
self.descricao = input("Insira a descrição do ganho: ")
self.valor = float(input("Insia o valor do ganho: "))
self.local = input("Inseria o local do ganho: ")
def __str__(self):
return f"Descrição do ganho: {self.descricao} \nValor: {self.valor} \nLocal: {self.local}"
We are not working with database to store information, which would make the entered data permanent.
The call of function could be something like:
# Passei a data como texto para deixar mais simples a coisa
eu = Usuario("[email protected]","UmaS3nhaB3mS3gura!!1!","01-01-2000")
The interaction would be something like
eu.alterar_saldo()
Escolha uma das opções abaixo
1. Gasto
2. Ganho
--> 2
Insira a descrição do ganho: Vendi meu carro
Insia o valor do ganho: 13000
Inseria o local do ganho: Feira de carro da cidade
And to see the history (look who put a list in the historical attribute, so you can check the history of all expenses and gains that have).
print(eu.historico[0])
Descrição do ganho: Vendi meu carro
Valor: 13000.0
Local: Feira de carro da cidade
UPDATE2
In this case, one may ask: "Why would I use an Object if a dictionary would work the same way?". This is a good question that I myself have asked myself (which I refused at first to use POO), until I felt the need of one thing: manipulation and organization.
You can quietly do the following:
clientes = {"nome":["Maria", "João", "Dom Pedro II"],
"idade":[31, 15, 195],
"comendo":[False, True, False],
"falando":[False, False, True]}
So far, no problem. But what if the list starts to extend further? For example, do I have a store with 100 customers? A list of 100 items would be difficult to see the information, also to access the specific information of each one (access Maria’s information without the error of accessing João), while the POO, you can make a dictionary too, as:
maria = Cliente("Maria", 31)
clientes = [{"maria":maria}, ...]
You can access information from Maria
just finding the right key, maybe it would be more interesting to use a key like CPF as the key of the dictionary, getting something like:
maria = Cliente("Maria", 31)
clientes = [{"098.765.432-10":maria}, ...]
This would already totally solve the problem of accessing the correct information, without worrying about the contents of the internal lists. But this is the smallest problem, the big question comes in manipulate information.
If, for example, maria
birthday, and want to add + 1 to her age, how would you? Would you have to create an external function def envelhecer()
and would have to look for a key feature, find the index where the information is maria
, find the right key and then change, if I have a class, I just put this function in and then do maria.envelhecer()
and Mary will have aged 1 year, as well as joao.envelhecer()
, dom_pedro.envelhecer()
, the same function for everyone, but this is the minor problem of handling.
The biggest problem is when you want climb your code; and if instead of name, age, eat and talk, you want to have the attribute andar
, comprar
(after all, they are customers), creditos_promocionais
(if customers are participating in a promotional campaign), data_de_compras_e_valor
(to have a list of the days that the customer visited and bought in your store, knowing also the value, to make a study of the customer and offer a promotion that pleases him, maybe creating a class the part only for that).
All of these above questions not only involve expanding the number of keys in the dictionary you would have, but also changing the information in them (and filling in all of them properly). Manipulating and expanding a dictionary externally can often result in unforeseen and unwanted errors, while in a class, as manipulations are standardized and internal to the class, fewer errors tend to occur, all objects in the class Cliente
will have the same characteristics and will be standardized structurally, expand is not a problem.
In this case, if you have already added attributes ("personal" characteristics) and methods (functions/actions), you could make a joao.data_de_compras_e_valor("01-02-2020",80.99)
and the information will already be updated in the object.
In practice, the advantage of an object is to work with volumes and volumes of data using little processing. Of course a POO does not replace a dictionary or vice versa, since I use enough dictionaries for fixed information and that will be little or nothing changed, serving precisely as a "de para", the above example of clients where I pass a key a primary key (CPF for example) and the value the object.
# Estrutura de um dicionário
dicio = {key:value} #{chave:valor}
clientes = {cpf:`Cliente`}
And use a list to aggregate these dictionaries:
clientes = [{"098.765.432-10":maria},
{"987.654.321-09":joao},
{"012.345.678-90":dom_pedro_segundo}]
There are no better or worse resources, but appropriate resources for each function. Things are excellent to suit the purpose of what they were created to, the paradigm of Object Orientation is one, dictionaries other, database other.
As I informed above, I am not using a database in the example, but with a POO, it would be easier for you to connect the table and access the right information, all standardized, tested and EASY MAINTENANCE for you and third parties.
And taking advantage of the issue of maintenance, sharing code and teamwork is much better using POO, because everyone will work on the same file, without the need to keep creating many substructures and files on the side, making the job easier for you and other people who will tamper with your code.
If you have any questions, comment on this answer that I do some complements the answer.
Could you specify better what you would like to be explained? It’s become a little wide
– Pilati
because and - the code there is self-explanatory. If you didn’t understand any specific part, ask about it. Creating another class, in one answer, that would do something like that doesn’t seem like it could clarify anything.
– jsbueno
and if im, that code would be perfectly usable on a micro-controller or built-in computer - is to see the Python framework on the platform you are on, and (1) create an instance of that class to be the "System Status" - that is, this instance will represent the state of the whole apparatus and (2) connect the methods of "talk," "stop talking," etc... as callbacks to be executed when I/O signals arrive. this connection is made with some call from the framework
– jsbueno
I agree with the others - "make an analogy with each attribute/syntax/parameter of an existing class so that it is even clearer to me how the construction of Python codes works" is a very wide question.
– jfaccioni
Posted a comment below devs.. in the last reply. Can you view? Thank you!!!!
– Curi