Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you set class attributes from variable arguments (kwargs) in python

Tags:

python

Suppose I have a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally.

I could set them manually, but it seems that variable parameters are common enough in python that there should be a common idiom for doing this. But I'm not sure how to do this dynamically.

I have an example using eval, but that's hardly safe. I want to know the proper way to do this -- maybe with lambda?

class Foo:     def setAllManually(self, a=None, b=None, c=None):         if a!=None:              self.a = a         if b!=None:             self.b = b         if c!=None:             self.c = c     def setAllWithEval(self, **kwargs):         for key in **kwargs:             if kwargs[param] != None                 eval("self." + key + "=" + kwargs[param]) 
like image 295
fijiaaron Avatar asked Nov 18 '11 18:11

fijiaaron


People also ask

How do you set a class attribute in Python?

Use the setattr() Function to Set Attributes of a Class in Python. Python's setattr() function is used to set values for the attributes of a class. In programming, where the variable name is not static, the setattr() method comes in very handy as it provides ease of use.

How do you pass Kwargs in a class Python?

Use the Python **kwargs parameter to allow the function to accept a variable number of keyword arguments. Inside the function, the kwargs argument is a dictionary that contains all keyword arguments as its name-value pairs. Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter.

How do you access class attributes in Python?

Accessing the attributes of a classgetattr() − A python method used to access the attribute of a class. hasattr() − A python method used to verify the presence of an attribute in a class. setattr() − A python method used to set an additional attribute in a class.

What does * args and * Kwargs mean?

*args passes variable number of non-keyworded arguments and on which operation of the tuple can be performed. **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed.


1 Answers

You could update the __dict__ attribute (which represents the instance attributes in the form of a dictionary) with the keyword arguments:

class Bar(object):     def __init__(self, **kwargs):         self.__dict__.update(kwargs) 

then you can:

>>> bar = Bar(a=1, b=2) >>> bar.a 1 

and with something like:

allowed_keys = {'a', 'b', 'c'} self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys) 

you could filter the keys beforehand (use iteritems instead of items if you’re still using Python 2.x).

like image 96
fqxp Avatar answered Nov 11 '22 17:11

fqxp