python - Set all class member variables in one line of code -
i have class several member variables initialize upon construction:
class myclass(): def __init__(self,var1,var2,var3,var4,var5,var6,var7,var8): self.var1 = var1 self.var2 = var2 self.var3 = var3 self.var4 = var4 self.var5 = var5 self.var6 = var6 self.var7 = var7 self.var8 = var8
is there pythonic way in single line of code?
i tried using eval
, didn't work of course:
class myclass(): def __init__(self,var1,var2,var3,var4,var5,var6,var7,var8): var in 'var1,var2,var3,var4,var5,var6,var7,var8'.split(','): eval('self.'+var+'='+var)
thank you.
x = 1 class myclass(object): def __init__(self, var1, var2, var3, var4, var5, var6, var7, var8): self.__dict__.update(locals()) del self.self y = 3 c = myclass(2, 3, 4, 5, 6, 7, 8, 9) var in 'var1 var2 var3 x y self'.split(): print var, ':', getattr(c, var, 'not present')
output:
var1 : 2 var2 : 3 var3 : 4 x : not present y : not present self : not present
this hack. drawbacks:
- if define
myclass
inside scope isn't top level (i.e. inside function), or ifself.__dict__.update(locals())
isn't first line in__init__
, may unwanted variables. - this or other magical solution messes inference linters (e.g. pycharm).
- this bypasses special attribute setting hooks such properties or
__setattr__
. in such situations, can use solution more deceze's:
class myclass(object): def __init__(self, var1, prop): k, v in locals().items(): setattr(self, k, v) del self.self @property def prop(self): return self._prop @prop.setter def prop(self, val): self._prop = val c = myclass(2, 3) print c.var1, c.prop, c._prop # 2 3 3
Comments
Post a Comment