Object Orientation (SUPER HELP)

Asked

Viewed 118 times

0

Here is a question that will require a more complete answer, will it happen?

Note this script that simulates a person’s behavior. Class is Person and methods are the possible behaviors. Someone can make an analogy with each attribute/syntax/parameter of an existing class so that it is even more clear to me how the construction of Python codes works (?).

They understood?

Follows the code:

from datetime import datetime

class Pessoa:
    ano_atual = int(datetime.strftime(datetime.now(), '%Y'))

    def __init__(self, nome, idade, comendo=False, falando=False):
       self.nome = nome
       self.idade = idade
       self.comendo = comendo
       self.falando = falando

    def falar(self, assunto):
        if self.comendo:
            print(f'{self.nome} não pode falar comendo.')
            return

        if self.falando:
            print(f'{self.nome} já está falando.')
            return

        print(f'{self.nome} está falando sobre {assunto}.')
        self.falando = True


    def parar_falar(self):
        if not self.falando:
            print(f'{self.nome} não está falando')
            return

        print(f'{self.nome} parou de falar.')
        self.falando = False


    def comer(self, alimento):
        if self.comendo:
            print(f'{self.nome} já está comendo.')
            return

        if self.falando:
            print(f'{self.nome} não pode comer falando.')
            return

        print(f'{self.nome} está comendo {alimento}.')
        self.comendo = True


    def parar_comer(self):
        if not self.comendo:
            print(f'{self.nome} não está comendo.')
            return

        print(f'{self.nome} parou de comer.')
        self.comendo = False

    def get_ano_nascimento(self):
        return self.ano_atual - self.idade

Thank you Devs!

PS. A beginner’s insight: we could use this code in the back end of a robot, for example, correct? Linking code to electronic functions. Does anyone have any idea how this could be done? Micro-controllers? Curiosity (I am researching in parallel).

  • Could you specify better what you would like to be explained? It’s become a little wide

  • 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.

  • 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

  • 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.

  • Posted a comment below devs.. in the last reply. Can you view? Thank you!!!!

1 answer

3


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 definitiating 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.

  • 1

    Speak brother! I think I get it. The Class is like a template and you instantiate some variable to use the methods/attributes belonging to this 'template', correct? That def init, I don’t know if I understood it correctly. The tbm modules have this extension in Python, it would be a kind of root directory of Cód.? Another thing: I’m not being able to make a parallel with other existing classes, list for example: it has no mandatory parameter. Some methods belonging to this class yes. Can you give me an ex. of using a mandatory parameter for a class? In this case we call the attribute right?

  • Exactly, the classes are molds with characteristics and actions preconceived to be filled (name, age) and used (speak, eat). As for def init, it comes from initialization (initializer), precisely where the initial characteristics will be, without the init, you do not have the initial attributes (name, age) to be defined. When you say "parallel" do you mean an interaction between them? As for the list, you can use an internal constructor def iter to iterate (create a list), so your class can behave like a list (or part of it).

  • I added an UPDATE to my code, if you want to know something else, just say I do a UPDATE2

  • Amazing brother. In your opinion, what is the advantage of using this paradigm instead of, for example, creating a dictionary with this information? Another thing, he agrees with me that in deepening in object-oriented programming you begin to understand a little more about the behavior of language?

  • Still on this constructive approach of the language that the POO gives us, could exemplify an existing class with its attributes (mandatory class variables) and internal methods?

  • I’m going to do an update2 talking about why to use a POO instead of dictionaries. As for the last question, I didn’t get it right, will I specify more? Depending, you can roll an update3

  • 1

    I’ll do this reading now, thank you brother. In the meantime, when I commented more about making a parallel I wanted to know basically how these concepts work within an existing class, so that I could put in perspective and understand better. Example: Does the str class have as its basic attribute the correct Object=' 'empty? Probably the content of this attribute goes into self.content or self.Object or whatever nomenclature is used to work within the internal functions of the class (methods). Follow the next comment...

  • This content is the string itself, which is sent as a parameter to the Len() method for example (correct me if I’m wrong). So, internally, Python would treat it more or less like this: def Len (self, string = self.Object, ....). The self.Object that is the content associated with def init which represents the string is passed as a parameter within def Len. It became clear? hehe. What I’m trying to do is this parallel with existing classes, hence my previous conclusion, when POO helps understand the internal construction of language, not all classes are called constructors.

  • In this case, you mean about the reserved functions as str, init, iter, repl? Or in the case of hierarchies when one inherits a class in another? 'Cause I couldn’t quite make out what I meant (sorry, I’m a little cold [and it’s not Coronavirus xD ])

Show 4 more comments

Browser other questions tagged

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