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__

understanding **kwargs and dictionary

Please go to 6:42 and pause the video. I see you have self then **kwargs in the init method. From previous lesson I understand **kwargs means you can send a dictionary and it will use the key and value in the dictionary.

In your console I see you created an instance of the class using

jubjub = Monster(color='red', sound='tweet')

inst color='red', sound='tweet' a tuple? I thought a dictionary have {} around it?

3 Answers

Yeah, exactly, what **kwargs does is just packing all the keyword arguments the function call received into a single variable kwargs, and it's a dictionary.

def foo(**kwargs):
  return kwargs

print foo(keyword1 = "hello", keyword2 = "world)
## => {'keyword1':'hello', 'keyword2':'world'}

Hi, Welby, I answered this question in quite a bit of detail in another forum post.

https://teamtreehouse.com/forum/how-does-a-new-attribute-like-adjectivemanxsome-become-a-kwargs-dictionary-or-its-item

Let me know if you have any more question after going through that post.

It explains it better...one more thing...how does this relate to packing and unpacking?

great..I understand how packing is related...can you give me an example of unpacking?

If I understand it correctly, example in the video shows how to unpack the **kwargs variable.

  def __init__(this, **kwargs):
    this.hit_points = kwargs.get('hit_points', 1)
    this.color = kwargs.get('color', 'yellow')
    this.weapon = kwargs.get('weapon', 'sword')
    this.sound = kwargs.get('sound', 'roar')