Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through constructor's arguments

I often find myself writing class constructors like this:

class foo:
    def __init__(self, arg1, arg2, arg3):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.

like image 514
rahmu Avatar asked Jul 20 '11 10:07

rahmu


1 Answers

The most Pythonic way is what you've already written. If you are happy to require named arguments, you could do this:

class foo:
    def __init__(self, **kwargs):
        vars(self).update(kwargs)
like image 189
Marcelo Cantos Avatar answered Oct 05 '22 19:10

Marcelo Cantos