** optional kwargs with default

1

It is common to find several apis that make use of KeyWordArgument of python. My question is how to use this refuse for object attributes. Sometimes when I use an API and I pass a parameter named param=True and the class I'm 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, for 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 to pass, and those that he does not inform have default values.

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

    
asked by anonymous 19.10.2016 / 22:45

1 answer

1
  

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

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

See 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

    
19.10.2016 / 23:34