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 Basic Object-Oriented Python Welcome to OOP Adding to our Panda

Neil Martin Orbase
Neil Martin Orbase
4,136 Points

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

2 Answers

Chris Freeman
Chris Freeman
Treehouse Moderator 67,464 Points

As 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
Neil Martin Orbase
4,136 Points

Hi @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?