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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…