I'm building a class with several optional attributes which can be set inline with the instance creation. Which is preferable?
Pass the attributes directly within __init__:
Or use **kwargs and check for each potential value:
I can see why the second method might be a bit more expensive, but it's not as if there's a lot of data being stored, and (self, name, **kwargs) looks cleaner and is easier to change if I need to add more arguments down the line.
Pass the attributes directly within __init__:
Code:
class Foo(object):
def __init__(self,
name,
bar1 = 0,
bar2 = 0,
bar3 = 0,
bar4 = 0,
notes = '',
comment = ''):
self.name = name
self.bar1 = bar
self.bar2 = bar2
self.bar3 = bar3
self.bar4 = bar4
self.notes = notes
self.comment = comment
Or use **kwargs and check for each potential value:
Code:
class Foo(object):
def __init__(self, name, **kwargs):
self.name = name
self.bar1 = kwargs['bar1'] if 'bar1' in kwargs else 0
self.bar2 = kwargs['bar2'] if 'bar2' in kwargs else 0
self.bar3 = kwargs['bar3'] if 'bar3' in kwargs else 0
self.bar4 = kwargs['bar4'] if 'bar4' in kwargs else 0
self.notes = kwargs['notes'] if 'notes' in kwargs else ''
self.comment = kwargs['comment'] if 'comment' in kwargs else ''
I can see why the second method might be a bit more expensive, but it's not as if there's a lot of data being stored, and (self, name, **kwargs) looks cleaner and is easier to change if I need to add more arguments down the line.