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 __init__

Using **kwargs and setattr

I keep getting "Bummer: Couldn't find 'Student'."

first_class.py
class Student:
    name = "Your Name"

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

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

    def praise(self):
        return "You inspire me, {}".format(self.name)

    def reassurance(self):
        return "Chin up, {}. You'll get it next time!".format(self.name)

    def feedback(self, grade):
        if grade > 50:
            return self.praise()
        return self.reassurance()
André Nårstad
André Nårstad
2,951 Points

As Kenneth writes in the teacher notes:

setattr lets me set attributes that I don't know about beforehand. I can, of course, go back and explicitly define a color attribute but what if the next user comes along and she wants a height or weight attribute? A year from now, Animal.init might be hundreds of lines long with attribute declarations! And some of those attributes will only apply to a few animals!

But...if I'm clever and use setattr, I can just happily accept any and all attributes that someone gives for a particular Animal instance without having to continually update init."

So try to use setattr with an for loop. That should do it.

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

EDIT: or just indent the one for loop you allready got in there :) saw it a little bit late..

1 Answer

I had to indent and I was missing the "s" in "items".