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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With