Add object validating if it exists

Asked

Viewed 71 times

1

I am creating these two methods in which the first worth the existence of a vehicle from your name. In the second, it is intended to add a new vehicle, validating first, if there is a vehicle with a given name, to avoid duplication of results. However, I always get the error described.

What can I do to prevent that from happening? Just the attribute preco_base is mutable

def exists_viatura(self, nome):
    for v in self.gestor:
        if v.nome == nome:
            return True
        else:
            print("Não existe nenhuma viatura")

def add_viatura(self, new_v):
    for v in self.gestor:
        new_v = Viatura(new_v.nome, new_v.modelo, new_v.tipo_electrica, new_v.preco_base)
        if g.exists_viatura(new_v.nome):
            print("Já existe uma viatura com esse nome")
    self.gestor.append(new_v)

Error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:/Users/sandr/PycharmProjects/projecto/Classes_Projecto.py", line 189, in add_viatura
    new_v = Viatura(new_v.nome, new_v.modelo, new_v.tipo_electrica, new_v.preco_base)
AttributeError: 'str' object has no attribute 'nome'
  • What it says in the error is that the parameter new_v is a string and therefore has no attributes.

  • Okay, and how can I refer to the object Car and have it entered on the list?

  • I think to see if it already exists just do so: existe = new_v in self.gestor, this will return False if there is no vehicle in the list gestor

1 answer

0


In Python to check if an object exists in a list is very simple. I believe that in your code would look like this:

def add_viatura(self, new_v):
    # verifica se existe a viatura na lista 'gestor'
    viatura_existe = new_v in self.gestor
    if viatura_existe:
        print("Já existe uma viatura com esse nome")
    else:
        self.gestor.append(new_v)
  • Now I have another problem (I’m trying to build an academic-level project with basic Pyhton programming). When a user rents a vehicle, an objceto is created in memory while Rental is active. This object has as attributes the start time of the rental, the nickname of the user, name of the vehicle and price per hour. Initially I created only one class. But it will be better to create an auxiliary class to define the methods to use to start Rentals?

  • I think if you create this helper class the code would be more organized and also make maintenance simpler

Browser other questions tagged

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