Printing all attributes of a class

Asked

Viewed 614 times

4

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 tasks:

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 variable u without having to write a print for each of the attributes, I can do this in Python?

1 answer

2

In Python there are special methods called often dunders(as they begin 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 with __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 function print built-in do Python invokes the special method (Dunder) __str__ of the object if it has defined, if it does not invoke the base class as in the example above, in the case object.

In your case you would like to print the object attributes without using a print for all its attributes, but it depends on who it will be shown to. In the 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__ 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’ve helped.

  • Thank you very much for the reply I got here!

  • Any doubt we’re here.

Browser other questions tagged

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