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 trialNeil Martin Orbase
4,137 PointsPlease help -- code is working interchangeably with other values and outputting the correct string.
This code is working interchangeably with different values when calling the Class and changing its values. Not sure what the issue is? It also keeps mentioning that 'Panda' is not defined, when Panda is indeed defined as the Class name. Please help.
class Panda:
species = 'Ailuropoda melanoleuca'
food = 'bamboo'
def __init__(self, name, age):
self.is_hungry = True
self.name = name
self.age = age
def eat(self):
self.is_hungry = False
return f'{self.name} eats {Panda.food}.'
panda_one = Panda('Bao Bao', 33)
panda_one.eat()
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsAs mentioned in this answer, need to use self.food
.
Instance attributes have two sources:
- instance attributes defined in the __init__ method
- class attributes defined outside of the methods
All of these are acceptable by using the self.
prefix. Instance attributes override (but do not over-write) class attributes.
Since “food” is not defined as an instance attribute, class attributes are then checked.
Post back if you need more help. Good luck!!!
Neil Martin Orbase
4,137 PointsHi @chris -- thank you so much! I didn't even attempt to try self.food
because my understanding was that it had to be declared within the __init__(self)
func code... e.g. def __init__(self, name, age, food):
then within that code: self.food = food
.. Can you please help me better understand how the self.food
works better to get this answer/output? (I've already gotten passed this question thanks to you, btw! But I just want to understand why this is better than using Panda.food
and also how does this work?
Chris Freeman
Treehouse Moderator 68,441 PointsI’ve updated my answer above.