Search object by PYTHON class attribute

Asked

Viewed 280 times

-1

Good afternoon, I wonder if I can find an object using an attribute

Example:

class Pessoa:



    def __init__(self, nome, idade, cpf)

        self.__nome = nome

        self.__idade = idade

        self.__cpf = cpf



pessoa1 = Pessoa('Thiago', 19, 000.000.000-00)

pessoa2 = Pessoa('Lucas', 18, 000.000.000-01)

There I want to access person1 only that passing Cpf.

Example:

Cpf 000.000.000-00

return

personal 1

Or something like that

  • How do you plan to search for this object? It will be the same terminal?

  • Yes, in case I will have some objects created, in the source code itself and according to what I type in the terminal, be automatically chosen which object will undergo the changes that a possible method will make

1 answer

0


This search is certainly feasible, but there is no "ready" Python implementation to do it. Python has no way of knowing a priori of the existence of the class Pessoa, or that each instance has an attribute __cpf.

In other words, you need to write the search logic on your own.

As an example, you could put all the people in a container, as a list:

pessoas = [pessoa1, pessoa2]

So, you can iterate over this list and find a specific person by comparing the attribute __cpf of each person with the CPF you are searching for (note that the CPF is a string, a numeric value will not work with dots and dashes):

for p in pessoas:
    if p.__cpf == '000.000.000-00':
        print('Pessoa encontrada:', p)

Generalizing as a function:

def busca_cpf(lista_pessoas, cpf_busca):
    for pessoa in lista_pessoas:
        if pessoa.__cpf == cpf_busca:
            return pessoa

Browser other questions tagged

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