Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python automate copying initializer arguments

Tags:

python

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

like image 662
Soldalma Avatar asked Aug 17 '13 17:08

Soldalma


1 Answers

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.

like image 115
BartoszKP Avatar answered Oct 20 '22 02:10

BartoszKP