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
You can achieve this using inspect module (EDIT: as correctly pointed out in comments, you actually don't need to import this module):
class A:
def __init__(self, a, b, c, d):
args = locals().copy()
del args['self']
self.__dict__.update(args)
a = A(1,2,3,4)
print a.a
print a.b
print a.c
print a.d
python test.py
1
2
3
4
You could wrap this into an utility function, just remembering not to take currentframe
but getouterframes
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With