Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bhuiyanmobasshir94/ce7061424a61f9fd3f582a8ec925787c to your computer and use it in GitHub Desktop.
Save bhuiyanmobasshir94/ce7061424a61f9fd3f582a8ec925787c to your computer and use it in GitHub Desktop.
How to create a class using variable number of variables in python
There is a known method to emulate a container for variables, which support both methods of access: by a variable's name and a string key.
class Vars:
def __init__(self, **kw):
self.__dict__.update(kw)
def __getitem__(self, key):
return self.__dict__[key]
def __setitem__(self, key, val):
self.__dict__[key] = val
def __contains__(self, name):
return name in self.__dict__
def __nonzero__(self):
return bool(self.__dict__)
def __iter__(self):
return iter(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __copy__(self):
return self.__class__(**self.__dict__)
def __repr__(self):
return 'Vars(' + ', '.join('%s=%r' % (k,v) for k,v in self.__dict__.items()) + ')'
>>> vars = Vars()
>>> vars.a = 1
>>> vars['b'] = 2
>>> print(vars)
Vars(a=1, b=2)
>>> print(vars['a'], vars.b)
1 2
>>> print(tuple(vars))
('a', 'b')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment