Using kwargs to initialize an object
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.



on 20 July 2010 at 09:06 Dag said …
How about for key, value in kwargs.iteritems(): setattr(self, key, value) and then you can hook @property to make stuff happen when an attribute is set?
on 20 July 2010 at 18:49 Al said …
Sometimes I also add:
def __getattr__(self, key):
if self.__dict__.has_key(key):
return self.__getattr__(key)
else:
return None
Then I can just do an "if myobj.attr != None" to test if an attribute is present, it simplifies the code and makes it more readable
on 21 July 2010 at 23:18 Dag said …
@Al Why not
hasattr(self, 'attr')? Also your code is recursive, you should callobject.__getattr__for new-style classes and modifyself.__dict__for old-style. Note thatvars(obj)is the proper way to accessobj.__dict__. The proper way to check for presence of a key isin:if key in vars(self). Yourelseis also redundant as is thereturn None.Just some pointers to help you write better code, don't mean to be mean!
Blog owner: <code/> is not a block element.