Printing all the attributes of a class [duplicate]


I have the following class:

class Usuario(object):
    def __init__(self):
        self.Nome = ''
        self.Email = ''
        self.SalarioBruto = 0.0
        self.SalarioLiquido = 0.0
        self.Cargo = ''
        self.Despesas = Despesas()
        self.Ganhos = Ganhos()
        self.TipoRelatorio = TipoRelatorio()

With the following assignments:

u = Usuario()
u.Nome = 'Tiago'
u.Email = '[email protected]'
u.SalarioBruto = 1.000
u.SalarioLiquido = 980.00
u.Despesas.Prioridade = 'Alta'
u.Despesas.Situacao = True
u.Despesas.Valor = 300.00
u.Despesas.Categoria = 'Alimentação'
u.Ganhos.Periodo.Fixa = '100'
u.Ganhos.Fonte = 'Freelancer'
u.TipoRelatorio.Semanal.DataInicial = '17/09/2018'
u.TipoRelatorio.Semanal.DataFinal = '24/09/2018'

I want to print the u variable without having to type print for each of the attributes, can I do this in Python?

asked by anonymous 17.09.2018 / 23:58

1 answer


In Python there are special methods often called dunders (since they start with two undercores) that are called under certain conditions when an object is being manipulated for example:

class Spam(object):

    def __init__(self, value):
        self.value = value

>>> obj = Spam("X")
>>> print(obj)
<__main__.Spam object at 0x7f5c1173f550>

How would you look like __str__ :

class Spam(object):

    def __init__(self, value):
        self.value = value

    def __str__(self):
        return "Meu valor é {0}".format(self.value)

>>> obj = Spam("X")
>>> print(obj)
Meu valor é X

The print built-in function of Python invokes the special method (dunder) __str__ of the object if it has defined it, if it does not call the base class as in the example above, in the object case.

In your case you would like to print the attributes of the object without using a print for all its attributes, but it depends on who the same will be shown. In case __str__ is used to display the object to the end user, already __repr__ , to display to the developer a representation of the object, it is good practice in __repr__ to define the initialization structure of the object in question, for example:

class Spam(object):

    def __init__(self, value):
        self.value = value

    def __repr__(self):
        return "{__class__.__name__}(value = {value})".format(__class__ == self.__class__, **self.__dict__)

>>> obj = Spam("X")
>>> repr(obj)
Spam(value = X)

I hope I have helped.

18.09.2018 / 00:42