Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting multiple object attributes at once

Is there a way to set multiple attributes of the same object on a single line, similarly to the way one assigns 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
like image 763
Csaba Koncz Avatar asked May 13 '15 10:05

Csaba Koncz


Video Answer


1 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 on class, but that would be less generic (i.e. apply only to that class instances).

Another answer mentions __dict__.update and it can be rewritten to get rid of quotes: obj.__dict__.update(a=1, b=2), however i would not recommend using this method: it doesn't work with properties and it might be hard to notice if you migrate from simple attributes to properties. Basically, __dict__ is "hidden" attribute, implementation detail, which you shouldn't use unless you really want to change implementation in some way.

like image 190
caryoscelus Avatar answered Sep 24 '22 12:09

caryoscelus