Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Objects __init__

How does using kwargs reduce repeated code?

The earlier kwargs code looked like this:

def __init__(self, hit_points=10,
                   color='yellow'):
    self.hit_points = hit_points
    self.color = color

The second example still has all the attributes listed twice, but in the kwargs.get() instead of in the parameter list:

def __init__(self, **kwargs):
    self.hit_points = kwargs.get('hit_points', 10)
    self.color = kwargs.get('color', 'yellow')

Either way you're writing the attribute names twice, so besides the benefit of optional arguments in the second example, I don't see how it's better.

1 Answer

jonlunsford
jonlunsford
15,480 Points

the kwargs statement allows multiple parameters to be passed in without breaking the method. In other words, it acts like a dictionary of key:value pairs for the parameters that are passed in. So if you decided to send in another parameter when you initialized like this it wouldn't break the code.

classname(hitpoints = 10, color = "yellow", skill = 50)

Oh, so by saying "we don't have to write each attribute name twice", I guess what he means is "we don't have to write the attribute once in __init__ and in the initialization call.