Python constructor with **kwargs

Asked

Viewed 168 times

1

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 similar cases to the one 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')

1 answer

4


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

Explicit is Better than implicit

In this case, if you want to leave the parameters as optional, just 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 mutable types, such as list.

When a default argument is evaluated in Python?

But if their values are immutable, initializing them with the value itself 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 previously know the parameters.

Browser other questions tagged

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