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


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

I understand and agree to the privacy policy