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.– Matheus Saraiva
I found this solution. But since it’s an old question who knows if there is a more elegant solution today.
– Matheus Saraiva