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 ?
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):
...
In a very pythonic way, it could be :
class MyClass:
def __init__(self, name, **kwargs):
self.name = name
self.__dict__.update(kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With