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

James J. McCombie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
James J. McCombie
Python Web Development Techdegree Graduate 21,199 Points

method.py

method, as a function, works in IDE shell, but wont pass in the quiz:

class Store: open = 9 close = 5

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

anyone know why

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

    def hours(open, close):

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

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

When defining a class method, it needs to refer to the class instance it is bound to. This is what allows the method to refer to the class and instance attributes. The reference is designated by the self parameter:

class Store:
    open = 9
    close = 5

    def hours(self):  # <-- add 'self' to parameter list. 'close' and 'open' are not needed
        # refer to attributes by using the 'self.' prefix to access 'open' and 'close'
        return "We're open from {} to {}.".format(self.open, self.close) 

Hi James,

You don't need to pass the open and close instance variables into the method; try with just the instance itself, self.

You can then use this to access the instance variables:

Store.py
class Store:
  open = 9
  close = 5
  def hours(self):
    return "We're open from {} to {}.".format(self.open, self.close)

I hope that makes sense.

Steve.

Haha! Thank you!! edits post :wink:

James J. McCombie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
James J. McCombie
Python Web Development Techdegree Graduate 21,199 Points

Thank you both, obvious from the lesson content in hindsight, but you have made it stick now, thanks, is it better to sometimes just accept the way things have to be written even though you are still a little confused about why...perhaps it will make sense to me one day.

I think that continued exposure to these concepts make them easier to understand as you work through the courses. Keep at it - it does all come together in the end!

proofreads :wink: