
Untitled
By: a guest on
May 21st, 2012 | syntax:
None | size: 1.35 KB | hits: 15 | expires: Never
How can you set class attributes from variable arguments (kwargs) in python
class Foo:
def setAllManually(self, a=None, b=None, c=None):
if a!=None:
self.a = a
if b!=None:
self.b = b
if c!=None:
self.c = c
def setAllWithEval(self, **kwargs):
for key in **kwargs:
if kwargs[param] != None
eval("self." + key + "=" + kwargs[param])
class Foo:
def setAllWithKwArgs(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class Bar(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
>>> bar = Bar(a=1, b=2)
>>> bar.a
1
allowed_keys = ['a', 'b', 'c']
self.__dict__.update((k, v) for k, v in kwargs.iteritems() if k in allowed_keys)
class SymbolDict(object):
def __init__(self, **kwargs):
for key in kwargs:
setattr(self, key, kwargs[key])
x = SymbolDict(foo=1, bar='3')
assert x.foo == 1
class Test:
def __init__(self, *args, **kwargs):
self.args=dict(**kwargs)
def getkwargs(self):
print(self.args)
t=Test(a=1, b=2, c="cats")
t.getkwargs()
python Test.py
{'a': 1, 'c': 'cats', 'b': 2}
class Foo:
def setAll(a=None, b=None, c=None):
for key, value in (a, b, c):
if (value != None):
settattr(self, key, value)