**kwargs optional with default

Asked

Viewed 116 times

1

It is common to find several Pis who make use of the KeyWordArgument python. My question is how to use this decline for object attributes. Sometimes when I use an API and pass a named parameter param=True and the class I am instantiating does not have an attribute with that name, I get an exception stating that the class does not have a property with that name, example:

>>> from gi.repository import Gtk
>>> a = Gtk.Button(label='Um botao')
>>> z = Gtk.Button(labelll='Um botao')
TypeError: gobject GtkButton doesn't support property 'labelll'

Question, how do I implement this in my classes? Another feature is also that the user can choose which parameters he wants to pass, and those he does not enter have default values.

The way I found to achieve this is by setting default values as in: def __init__(self, paran1=True, paran2=False, paran3='anything') But how to achieve the same effect using: def __init__(self, **kwargs) ?

  • Reasoned a little I think **kwargs does not make sense if you have a specific amount of parameters, as is the case of attributes of a class. I think that **kwargs only makes sense if you have a function that can receive any number of parameters like: def soma_os_parametros(**kwargs):. Mas **kwargs is useful when you have a good amount of parameters . Imagine an object with 10 attributes where all can be passed via __init__ and all having standard value. **kwargs would save typing.

  • I found this solution. But since it’s an old question who knows if there is a more elegant solution today.

1 answer

1


Another feature is also that the user can choose which parameters he wants to pass, and those he does not enter have values default.

Assuming kwargs is a dictionary, you can use the method dict.get to get a value, and if you prefer, set a default value if you do not enter one and the key does not exist, an exception KeyError is launched.

Take an example:

class Pessoa(object):
    def __init__(self, **kwargs):
        self.nome = kwargs.get('nome', 'Joao')
        self.peso = kwargs.get('peso', 80)
        self.idade = kwargs.get('idade', 60)

    def foo(self):
        print (self.nome, self.peso, self.idade)

pessoa = Pessoa(peso = 70, idade = 50)  # nome não foi indicado, Joao vai ser o padrão
pessoa.foo()  # Joao 70 50

See DEMO

  • If you want to use a dictionary instead of variables, you can do thus.

Browser other questions tagged

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