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

tomtrnka
tomtrnka
9,780 Points

Passing a dictionary into **kwargs ???!!

class Thief:
    sneaky = True

    def __init__(self, name, sneaky=True, **kwargs):
        self.name = name
        self.sneaky = sneaky

        for key,value in kwargs.items():
            setattr(self, key, value)

I tried to pass a dictionary as value into the **kwargs parameter but it doesnt work. No attributes age or skin were created for the instance 'brother'.

brother = Thief("Ivan", {'skin':'too soft', 'age':'too old'})

That means I can pass only variable arguments into **kwargs (meaning: age='too old', skin='too soft') ?? Or is there a way to extract this dictionary from **kwargs and assign the values into variables ?? Thanks a lot!

1 Answer

Michael Hulet
Michael Hulet
47,912 Points

You totally can pass in a dictionary for attributes like you're trying to do, you just also have to unpack it at the call site, like this:

# Notice the extra ** before the dictionary here
sister = Thief("Emily", **{'skin': 'kinda rough tbh', 'age': 'younger than me'})
print(sister.skin)
>>> kinda rough tbh

The extra ** is what tells Python that it should use that dictionary as keyword arguments. Otherwise, it'll think it's just another parameter. For example, look at what happens when you print out brother.sneaky in the code you posted 😉

brother.sneaky
>>> {'skin': 'too soft', 'age': 'too old'}
tomtrnka
tomtrnka
9,780 Points

Thank you! makes sense :)