To expand on gruszczy
s answer, I have used a pattern like:
class X:
x = None
y = None
z = None
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
if hasattr(self, k):
setattr(self, k, v)
else:
raise TypeError('Unknown keyword argument: {:s}'.format(k))
I like this method because it:
- avoids repetition
- is resistant against typos when constructing an object
- works well with subclassing (can just
super().__init(...)
) - allows for documentation of the attributes on a class-level (where they belong) rather than in
X.__init__
Prior to Python 3.6, this gives no control over the order in which the attributes are set, which could be a problem if some attributes are properties with setters that access other attributes.
It could probably be improved upon a bit, but I'm the only user of my own code so I am not worried about any form of input sanitation. Perhaps an AttributeError
would be more appropriate.