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)
    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.

Want content like this in your inbox each workday irregularly? No BS, spam or tricks... just useful content:

I understand and agree to the privacy policy