List of objects in Python

2

I'm doing a function that returns an object list. Code snippet:

def guarda_word(lista_palavras,lista_objeto,indice):

    for i in lista_palavras:
        if bool(lista_objeto) == True: # a list de objeto esta vazia
            i = PalavraIndices(i)
            i.add_item(indice,1)
            lista_objeto.append(i)
        elif i not in lista_objeto: # o elemento da lista de palavras ainda nao tem um objeto
            i = PalavraIndices(i)
            i.add_item(indice,1)
            lista_objeto.append(i)
        else:
            i.add_item(indice,1)
    return lista_objeto

lista_objeto = guarda_word(palavras_A,lista_objeto,'arquivoA')

print(lista_objeto)

The problem is, when I start this list of objects on the screen .. it goes like this:

[<__main__.PalavraIndices object at 0x005E6970>, <__main__.PalavraIndices 
object at 0x005E6990>, <__main__.PalavraIndices object at 0x005E69B0>, 
<__main__.PalavraIndices object at 0x005E69D0>, <__main__.PalavraIndices 
object at 0x005E69F0>, <__main__.PalavraIndices object at 0x005E6A30>, 
<__main__.PalavraIndices object at 0x005E6A50>, <__main__.PalavraIndices 
object at 0x005E6A70>, <__main__.PalavraIndices object at 0x005E6A90>, 
<__main__.PalavraIndices object at 0x005E6A10>, <__main__.PalavraIndices 
object at 0x005E6AB0>, <__main__.PalavraIndices object at 0x005E6AD0>, 
<__main__.PalavraIndices object at 0x005E6AF0>]

Does anyone know the proque is not just showing the name of each object in this list?

    
asked by anonymous 07.10.2017 / 20:34

2 answers

4

You should add a __repr__(self) method to the instantiated object, which will return a string as you want it to appear on screen.

See this for more information.

def __repr__(self):
     return str(self.__dict__)
    
07.10.2017 / 20:51
3

If the goal is just to show only the class name, you can do this:

class Foo:
    pass
print(Foo().__class__.__name__) # Foo

DEMONSTRATION

But if you want something more personalized for each object (instance of the class) depending on the entries you can do for example:

class Foo:
    def __init__(self, bar):
        self.bar = bar
    def __repr__(self):
        return 'Class {} em que na sua variável de instância bar é {}'.format(self.__class__.__name__, self.bar)

print(Foo('hey')) # Class Foo em que na sua variável de instância bar é hey
print(Foo('lol')) # Class Foo em que na sua variável de instância bar é lol
print(Foo('bar')) # Class Foo em que na sua variável de instância bar é bar

DEMONSTRATION

But if you do not declare this method, or in this case __str__(self) , the output for this is just that 'general description'.

There are some examples of very often used classes that work just like this:

from decimal import Decimal

print(Decimal('10.5')) # 10.5
print(Decimal('21.2')) # 21.2

DEMONSTRATION

    
07.10.2017 / 21:01