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 ?

1
  • 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, 2017 at 8:24

3 Answers 3

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):
        ...
1
  • 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, 2017 at 8:31
1

In a very pythonic way, it could be :

class MyClass:
    def __init__(self, name, **kwargs):
        self.name = name
        self.__dict__.update(kwargs)
1
  • 2
    Won't work for descriptors and slots. Jul 25, 2017 at 8:27
-1

You can use *args i.e

def __init__(self, *args):
    self.args = args

Not the answer you're looking for? Browse other questions tagged or ask your own question.