Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 21st, 2012  |  syntax: None  |  size: 1.35 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How can you set class attributes from variable arguments (kwargs) in python
  2. class Foo:
  3.     def setAllManually(self, a=None, b=None, c=None):
  4.         if a!=None:
  5.             self.a = a
  6.         if b!=None:
  7.             self.b = b
  8.         if c!=None:
  9.             self.c = c
  10.     def setAllWithEval(self, **kwargs):
  11.         for key in **kwargs:
  12.             if kwargs[param] != None
  13.                 eval("self." + key + "=" + kwargs[param])
  14.        
  15. class Foo:
  16.   def setAllWithKwArgs(self, **kwargs):
  17.     for key, value in kwargs.items():
  18.       setattr(self, key, value)
  19.        
  20. class Bar(object):
  21.     def __init__(self, **kwargs):
  22.         self.__dict__.update(kwargs)
  23.        
  24. >>> bar = Bar(a=1, b=2)
  25. >>> bar.a
  26. 1
  27.        
  28. allowed_keys = ['a', 'b', 'c']
  29. self.__dict__.update((k, v) for k, v in kwargs.iteritems() if k in allowed_keys)
  30.        
  31. class SymbolDict(object):
  32.   def __init__(self, **kwargs):
  33.     for key in kwargs:
  34.       setattr(self, key, kwargs[key])
  35.  
  36. x = SymbolDict(foo=1, bar='3')
  37. assert x.foo == 1
  38.        
  39. class Test:
  40.     def __init__(self, *args, **kwargs):
  41.         self.args=dict(**kwargs)
  42.  
  43.     def getkwargs(self):
  44.         print(self.args)
  45.  
  46. t=Test(a=1, b=2, c="cats")
  47. t.getkwargs()
  48.  
  49.  
  50. python Test.py
  51. {'a': 1, 'c': 'cats', 'b': 2}
  52.        
  53. class Foo:
  54.     def setAll(a=None, b=None, c=None):
  55.         for key, value in (a, b, c):
  56.             if (value != None):
  57.                 settattr(self, key, value)