Setting multiple attributes of objects at the same time

Is there a way to set multiple attributes of the same object on the same line, similar to assigning values ​​to multiple variables?

If I can write

a,b,c=1,2,3

      

I would like to have something like

someObject.(a,b,c)=1,2,3

      

Having the same effect as

someObject.a=1
someObject.b=2
someObject.c=3

      

+3


source to share


4 answers


def setattrs(_self, **kwargs):
    for k,v in kwargs.items():
        setattr(_self, k, v)

      

Use this function like this:

setattrs(obj,
    a = 1,
    b = 2,
    #...
)

      



You can also define this function in a class, but this will be less general (i.e. apply only to instances of that class).

Another answer mentions __dict__.update

and can be rewritten to get rid of the quotes: obj.__dict__.update(a=1, b=2)

however I would not recommend using this method: it does not work with properties and it can be hard to see from simple attributes to properties. Basically, __dict__

this is a "hidden" attribute, an implementation detail that you shouldn't use unless you really want to change the implementation in any way.

+4


source


attributes = ['a', 'b', 'c']
values = [1, 2, 3]
for attr, val in zip(attributes, values):
    setattr(obj, attr, val)

      



+1


source


First of all, you can do the same with object attributes as with other variables:

someObject.a, someObject.b, someObject.c = 1,2,3

      

Not sure if that's what you mean already. If you want to update arbitrary attributes (in a function, for example), you can take advantage of the fact that Python objects store their attributes in a dict, which update () supports :

someObject.__dict__.update({"a":1, "b":2, "c":3})

      

However, this should only be done with caution! If you suggest this in a function, any attribute of someObject can be changed using this function and even new attributes can be inserted!

+1


source


Here's the pythonic way:

attrs = {'a': 1, 'b': 2, 'c': 3}

map(lambda item: setattr(someObject, *item), attrs.iteritems())

      

+1


source







All Articles