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 trialJesus Cardenas
1,334 PointsHow do I return name attribute in a string?
How do I return name attribute in a string
class Panda:
species = 'Ailuropoda melanoleuca'
food = 'bamboo'
name = 'Bao Bao'
def __init__(self, name, age):
self.is_hungry = True
self.name = name
self.age = age
def eat(self):
self.is_hungry = False
self.food = 'bamboo'
self.name = 'Bao Bao'
return (f'{name} eats {food}')
1 Answer
Jennifer Nordell
Treehouse TeacherHi there, Jesus Cardenas! There are a few things going on here. First, you've added a name
to the top, which isn't needed. Also, in your eat()
method you've redefined self.name
and self.food
. The class has an attribute of food
because all pandas eat bamboo. Fluffy the panda eats bamboo and Bao Bao eats bamboo. It would be odd to encounter a panda named "Bandit" that for some odd reason eats scrambled eggs.
When we add a new Panda
the __init__
gets called and at that time we send in a name for that panda. Sure, there may be two pandas with the same name, but it would be odd to have every panda in every zoo named "Fluffy". How on earth would you tell them apart? The self
refers to the specific panda that we're talking about.
So your eat
method only really needs two lines. It needs to set is_hungry
to False
, which it did just fine. And then return the name of the panda along with the food it ate.
return f"{self.name} eats {self.food}"
Hope this helps!
Jesus Cardenas
1,334 PointsJesus Cardenas
1,334 Pointsclass Panda: species = 'Ailuropoda melanoleuca' food = 'bamboo'
Yes that helped me understand it more but when I call the eat method, I don't get the correct message. How do use the name attribute that is passed in to the instance.
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse TeacherJesus Cardenas To test this outside of the challenge you'd first need to create a
Panda
. Here, I'm going to create a panda named "Fluffy" who is age 3 then print out what is returned by the eat method.This outputs:
Fluffy eats bamboo
Hope this helps!