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

haakon Guttormsen
haakon Guttormsen
2,157 Points

how to "run" a method within a class?

I want to be able to "run" whats going on within a method of a class. Is there a way to this? I want to run the praise-method below:

class Student:
    name = "håkon"
    def praise (self):
        return ("I like your hair today {}".format(self.name))

Student.praise(self)

You need to first instantiate an instance of the class. Then call the method.

haakon = Student()
haakon.praise()

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

If you use the '@classmethod' decorator, the code should run the way you described. If you left off the decorator, you cannot execute the praise method directly, but would be required to instantiate the class object, like s=Student() and s.praise()... see below

# here I run command line python

C:\Users\Jeffrey>\Python36\python.exe
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Student:
...     name = "håkon"
...     @classmethod
...     def praise (self):
...         return ("I like your hair today {}".format(self.name))
...
>>> Student.praise()
'I like your hair today håkon'
# without the class method, you can still use the praise method after you instantiate the class object
>>> s = Student()
>>> s.praise()
'I like your hair today håkon'