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 trialDaniel Lounsbury
1,744 PointsHow do I add attributes to student?
I am at a loss as to how add additional attributes on an instance.
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
28,046 PointsHi 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.
Mustafa Başaran
28,046 PointsHi 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!
Daniel Lounsbury
1,744 PointsDaniel Lounsbury
1,744 PointsHi 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
1,744 PointsDaniel Lounsbury
1,744 PointsI appreciate your help, I got there in the end