Using kwargs to initialize an object

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)
    def set_id(self, id=None):
    def set_value2(self,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.

comments powered by Disqus