Python builder with ** kwargs

0

I would like to know if the use of ** kwargs in a constructor is the best alternative or if there is a better path for cases similar to the ones below:

   class Duvida(object):

       def __init__(self, **kwargs):

           self.formato=''
           self.nota='5'

           if 'formato' in kwargs.keys():
               self.formato=kwargs['formato']
           if 'nota' in kwargs.keys():
               self.nota=kwargs['nota']


   q=Duvida(formato='Formato Personalizado')
    
asked by anonymous 07.12.2017 / 18:53

1 answer

4

The best way is to explicitly state the arguments. Quoting Zen of Python :

  

Explicit is better than implicit

In this case, if you want to leave the parameters as optional, simply initialize them with a default value:

class Duvida(objet):
    def __init__(self, formato=None, nota=None):
        self.formato = formato if formato is not None else ''
        self.nota = nota if nota is not None else '5'

duvida = Duvida(formato='Formato Personalizado')

This avoids the problem of initializing parameters with changeable types, such as list.

When is a default argument evaluated in Python?

But if your values are immutable, initializing them with your own value should not generate any side effects in the program:

class Duvida(objet):
    def __init__(self, formato='', nota='5'):
        self.formato = formato
        self.nota = nota

duvida = Duvida(formato='Formato Personalizado')

Use only *args and **kwargs when you do not know the parameters previously.

    
07.12.2017 / 19:05