How to create property in a Python object?

Asked

Viewed 64 times

0

How can I create an object with property and add to an object list using python?

I have a funtion that expects a return from a list of products, this return is used by other futions and do not want to change the type of return, so I’m trying to assemble the same object of type list.

The idea is to simply add an object to a list, but I’m having some mistakes every time I try something different.

As in the case below I have the error:

0:"'Object' Object has no attribute 'Urltermo'"

Right on the line produto.UrlTermo = termo.TermoDescricao

buscaproduto: list = []

produto: object = object()
produto.UrlTermo: str
produto.UrlTermo = termo.TermoDescricao
buscaproduto.append(produto)
  • 1

    Question: why not create the class Produto to use there?

  • @Woss, the funtion that calls this code does not expect a typed type, also do not know if I can make the append of a type to list and cause no problem later

  • 2

    In Python there is no "typed type". You can do it quietly.

1 answer

0

After some research and @Woss comment, I was able to solve with a class.

class Produto(object):
    def __init__(self, termo: str, qtdRegistros: int, descricao:str, tipoConsulta:str):
        self.UrlTermo = termo
        self.QtdRegistros = qtdRegistros
        self.Descricao = descricao
        self.TipoConsulta = tipoConsulta

Calling in the following way:

produto = Produto(termo.TermoDescricao, 1, termo.TermoBusca, 'Termo')
buscaproduto.append(produto)
  • 2

    If you want, also search by dataclasses

Browser other questions tagged

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