Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to initialize an object with a lot of parameters and default value [duplicate]

I need to create a class wich take a lot of parameters.

class Line:

    def __init__(self, name, nb = None, price_unit = None, total = None, 
                 unit = None, time = None, session = None ):

Every attribute will get the same name and the same value as the parameter passed to __init__().

So, of course i could do :

class MyClass:

    def __init__(self, name, nb = None, price_unit = None, total = None, 
                 unit = None, time = None, session = None ):
        self.name = name
        self.nb = nb
        self.price = price
        self.price_unit = price_unit
        self.total = total
        self.unit = unit
        self.time = time
        self.session = session

But that's a really heavy notation and doesn't seems pythonic to me. Do you know a more pythonic manner to do it ?

like image 449
Peni Avatar asked Jul 25 '17 08:07

Peni


2 Answers

Since you're setting defaults for all the keyword arguments to None, you can do the more readable:

class MyClass:

    def __init__(self, name, **kwargs):
        self.name = name
        for attr in ('nb', 'price_unit', 'total', 'unit', 'time', 'session'):
            setattr(self, attr, kwargs.get(attr))

However, I think your initial approach is pretty standard too, although you can improve it by removing the whitespaces between the arguments and their default values.

class MyClass:
    def __init__(self, name, nb=None, price_unit=None, total=None, 
                 unit=None, time=None, session=None):
        ...
like image 139
Moses Koledoye Avatar answered Nov 04 '22 18:11

Moses Koledoye


In a very pythonic way, it could be :

class MyClass:
    def __init__(self, name, **kwargs):
        self.name = name
        self.__dict__.update(kwargs)
like image 1
Cédric Julien Avatar answered Nov 04 '22 16:11

Cédric Julien