Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Instant Objects __init__

Daniel Lounsbury
Daniel Lounsbury
1,744 Points

How do I add attributes to student?

I am at a loss as to how add additional attributes on an instance.

first_class.py
class Student:
    name = "Shawn"

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

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

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

2 Answers

Mustafa Başaran
Mustafa Başaran
28,021 Points

Hi Daniel,

the init() function does that for you via **kwargs argument. **kwargs are key value pairs which can be set as attributes to the instance of the class when the new instance is created.

Though you need to change your code slightly within the init() part. You are missing keys and values.. **kwargs, right?

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

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

Once you have your init(), **kwargs and setattr() in place, you can assign as many attributes as possible to your instances of the Student class.. Such as

shawn = Student(name='shawn', major='chemistry', likes_coding=True, year=2)

I hope this helps.

Daniel Lounsbury
Daniel Lounsbury
1,744 Points

Hi Mustafa, thank you for your help. I tried your suggestion and it got me closer but now I am getting the error msg 'Bummer: Exception: setattr expected 3 arguments, got 2"

can you help me by:

1) highlighting what the first 2 arguments were 2) advise me where the third argument would be inserted

Thank you for your time on this. I really appreciate it.

Daniel Lounsbury
Daniel Lounsbury
1,744 Points

I appreciate your help, I got there in the end

Mustafa Başaran
Mustafa Başaran
28,021 Points

Hi Daniel, I am sorry that I could not get back to you immediately.. but it is very nice to hear that you solved it on your own. Great!