5

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 ?

Peni
  • 626
  • 1
  • 7
  • 18
  • You are already using the pythonic way to initialize an object with default value. The issue comes from your Class API. If there is too much arguments, you should considere to refactor it. – Delgan Jul 25 '17 at 08:24

3 Answers3

10

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):
        ...
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • In the **kwargs case you can also init the object with only the arguments that you want like: MyClass(name, price_unit=value, total=value2) – Lucian Jul 25 '17 at 08:31
1

In a very pythonic way, it could be :

class MyClass:
    def __init__(self, name, **kwargs):
        self.name = name
        self.__dict__.update(kwargs)
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
-1

You can use *args i.e

def __init__(self, *args):
    self.args = args
Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108