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

I need to create a class that requires a lot of parameters.

class Line:

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

Each attribute will receive 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 this is really a heavy notation and does not seem to me pythonic. Do you know a more pythonic manner?

+4
source share
3 answers

Since you are setting default values โ€‹โ€‹for all keyword arguments None, you can make it 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))

, , , , .

class MyClass:
    def __init__(self, name, nb=None, price_unit=None, total=None, 
                 unit=None, time=None, session=None):
        ...
+8

pythonic :

class MyClass:
    def __init__(self, name, **kwargs):
        self.name = name
        self.__dict__.update(kwargs)
+1

You can use * args ie

def __init__(self, *args):
    self.args = args
-1
source

Source: https://habr.com/ru/post/1682189/


All Articles