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 (retired) Objects Create a Class with a Method

chiu szu ting
chiu szu ting
2,318 Points

method in class help!

there must be something wrong in my programming below,though it pass the task. if i delete the two attributes ''open=7","close=21" in def, then it will return a NameError: name 'open' is not defined.i don't know why it happens.

method.py
class Store(): 
    open = 7
    close = 22
    a='we open from {} to {}'
    def hours(self):
        open = 7
        close = 22
        return self.a.format(open,close)

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Yes, your code does pass, but that's because you've redefined the variables locally inside the method. The better way to do this would be to format the string with the properties of the object. And you were on the right track! You used self.a as the string to format. What we were looking for is to format the string with self.open and self.close. So if you remove your open and close variables from the method we get something that should look like this:

def hours(self):
    return self.a.format(self.open,self.close)

Hope this clarifies things! :sparkles:

chiu szu ting
chiu szu ting
2,318 Points

the concept of class is still unclear and difficult to me , but your answer certainly helps, thank you ;)