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__

Welby Obeng
Welby Obeng
20,340 Points

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

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

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'}
William Li
PLUS
William Li
Courses Plus Student 26,868 Points

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.

Welby Obeng
Welby Obeng
20,340 Points

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

Welby Obeng
Welby Obeng
20,340 Points

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

Iain Diamond
Iain Diamond
29,379 Points

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')