Constructors in Python often look like this:
class SomeClass:
def __init__(self, a, b = None, c = defC):
self.a = a
self.b = b or []
self.c = c
Is there a shortcut for this, e.g. to simply define __init__(self,**kwargs)
and use the keys as properties of self
?
Yes:
One idiom I've seen is
self.__dict__.update(locals())
. If you run it right at the beginning of the method, this will update the object's dictionary with the arguments (since those are the only locals at the beginning of the method). If you pass in**kwargs
you can doself.__dict__.update(**kwargs)
.Of course, this is a fragile approach. It can lead to puzzling bugs if you accidentally pass in an argument that masks an existing attribute. For instance, if your class has a
.doSomething()
method and you accidentally passdoSomething=1
to the constructor, it will override the method and cause an error later if you try to call that method. For this reason it's better not to do this except in certain trivial cases (e.g., some sort of proxy object whose only purpose is to serve as a "bag" holding a few attributes).One problem with
is that it includes
self
, so you getself.self
. It would be better to filterself
out oflocals()
eg.
You can defend against accidentally overwriting methods with this variation
If you don't want it to fail silently, you could also check beforehand like this