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

luke hammer
luke hammer
25,513 Points

Object-Oriented Python

I don't understand why this code is not working.

method.py
class Store:
  open = 5
  close = 17
  def hours(self):
    return "We're open from {} to {}.".format(open, close)
Robert White
Robert White
2,599 Points

Stuck on this part of the code challenge as well. This is beginning to drive me mad because its the intro video and we haven't yet been introduced to the techniques mentioned in Jon Hockleys reply. Its also seemingly so simply that its hard to see whats missing.

luke hammer
luke hammer
25,513 Points

my problem above was just forgetting to use "self." for the open and close vars.

1 Answer

Jon Hockley
Jon Hockley
3,781 Points

Hi Luke,

I'm not sure where you are up to with your learning, but here are a few pointers to help you along (If you don't recognise some of this; you'll sure run into it before long, and it should ring a few bells!):

  • Although it isn't mandatory, an init method (or constructor as it's known in other languages) would be good for setting your open and close hours when you initialise any new store object.
  • I would then also recommend using 'getter' and 'setter' methods for doing just that on the open and close values (I haven't used any setter methods in my example below just to save time)
  • When you need to access any variables that you have definied in your class, you do this via self._____ (You can see how I have achieved this in my example using the getter methods)

example

class Store:
    def __init__(self, open, close):
        self._open = open
        self._close = close

    def get_open(self):
        return self._open

    def get_close(self):
        return self._close

    def display_hours(self):
        print("We're open from {} to {}".format(self.get_open(), self.get_close()))


store = Store(9, 5)
store.display_hours()
# Prints "We're open from 9 to 5"

Hope this helps!