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 Instant Objects Method Arguments

Ashley Keeling
Ashley Keeling
11,476 Points

what is **kwargs?

in the video he uses kwargs and I am not sure what it means/does

1 Answer

AJ Salmon
AJ Salmon
5,675 Points

**kwargs takes any number of normal python keyword arguments, like name = 'Stephen' or num = 3 and puts them into a dictionary- {'name' : 'Stephen', 'num' : 3}. Using **kwargs in the parameter of a method like Kenneth does, in this case, the __init__, will simply take any extra keyword/value pairs that aren't explicitly required when creating an instance of the class and put them into a dict. Then, he uses setattr to create an attribute for that class, using the dictionary that **kwargs created. The name of the attribute is the key in the dict, and the value is, well, the value. Say you create an instance of the class Thief, like this:

>>> from characters import Thief
>>> criminal = Thief('AJ', weapon='sword', health=10)

Now, even though we didn't create weapon or health attributes in the __init__, setattr creates them with the power of **kwargs. So, when you look to see if the instance has those attributes, they're there.

>>> criminal.name
'AJ'
>>> criminal.sneaky
True
>>> criminal.weapon
'sword'
>>> criminal.health
10

**kwargs accepts as many keyword arguments as you'll give it. You can also give it nothing. The only required fields are the ones you tell it will definitely be there. In this case, that's only the name attribute.

Thanks it helped me a lot!! But I don't get everything did he use 'setattr' to make an attribute from the dictionarie?

AJ Salmon
AJ Salmon
5,675 Points

Yes, that's exactly what setattr does! In my above example, weapon='sword' and health='10' are both collected as kwargs, and then packed into a dict. setattr creates attributes with this dict on the spot, using the dictionary key as the attribute name, and then that attribute is set to the corresponding dictionary value. Hope this helps!

Thanks again!