Saturday, 17 August 2013

Python automate copying initializer arguments

Python automate copying initializer arguments

Python classes have an initializer method called init. Frequently the
initializer accepts several arguments that are copied to eponymous
attributes.
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
This is a lot of work and feels "unpythonic" to me. Is there a way to
automate the process?
I thought maybe something along these lines (pseudocode below) could work:
for x in __init__.argument_names:
exec('self.' + x + ' = ' + x)
I know calling exec in this way would not be good practice. But maybe the
Python development team has created a safe and equivalent way of
automating this task.
Any suggestions?
FS

No comments:

Post a Comment