Using kwargs to initialize an object

Last Update: 20.07.2010. By kerim in python | snipplet

Way to many (possible and/or optional) parameters for a class? Here is a 5 second tip for all those old style Java-type-programmers…

Use kwargs, simple setter methods and run through the keys.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
class myClass():
    def __init__(self, **kwargs):
        for key in kwargs:
            f = getattr(self, 'set_' + key)
            f(kwargs[key])
    def set_id(self, id=None):
        print(id)        
    def set_value2(self,value):
        print(value)

c=myClass(id="myID", value2=2)

PS: Of course you might wanna wrap that with some exception handling in case some key is wrong.