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 trial

Python Object-Oriented Python (retired) Objects Create a Class with a Method

Matthew Rigdon
Matthew Rigdon
8,223 Points

Class/Method Explanation

First, could someone assist me with the problem below.

Here is the questions:

Now, add a method named hours that returns "We're open from {} to {}.". Replace the first placeholder with the open time and the second with the close time. Remember you need to pass keywords to .format() if your placeholders have names.

I know how I can do this with a function, but using a method nestled in a class is confusing. I am not sure how to write this.

Second, can anyone explain methods and classes in simpler terms?

Thank you!

method.py
class Store:
  open = 9
  close = 5

  def hours(self):
    return self."We're open from {} to {}.".format(open, close)

2 Answers

The class store is like a generic form of a thing called store. Though you won't encounter it in this challenge ( I don't think) you can have instances of of 'store' that will take on the attributes of 'store' (open and close)

class Toy(Store)

class Grocery(Store)

would create two different instances of Store. Again, this is tangential to your question.

The method is just a function inside of a class so it is given a different name. You use the 'self' argument to reference what it is you are passing to the method (function). Since you are referencing Store in this method, I believe this is correct, you need to put the self in front of open and close in the format statement. It is kind of the same thing as saying Store.open and Store.close. Also you will need to remove the self at the beginning of the return statement.

Did that help at all?

Matthew Rigdon
Matthew Rigdon
8,223 Points

Yes, the explanation/description helped, but the code still doesn't work. I wrote this:

  def hours(self):
    return "We're open from {} to {}.".format(self.open, self.close)

Thanks too!

EDIT: I changed the code, and I got it to work using your suggestions. Thanks!

Benjamin Verspeak
Benjamin Verspeak
10,940 Points

still helping people 2 years later :) thank you!

Awesome! Nice work.

Feel free to give me an upvote if your feeling saucy :-)