Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Sometimes it just doesn't make sense to make an instance of a class before we call a method on it. Python gives us a decorator named `@classmethod` that allows us to create an instance of the class from inside of it. Let's see how to use this to make user creation easier.
@classmethod
Let's talk more about @classmethod
. Let's make a class to represent an email.
class Email:
to = None
from = None
subject = None
content = None
If I want to make a new Email
using the class constructor, that's easy. email = Email()
and then fill in the attributes. Assuming there's a __init__()
that handles setting the attributes, I can probably do that in one step.
But what if I want a method for immediately creating and sending the email? I either have to create an instance and then call .send()
on the instance or I need a @classmethod
way of generating one.
class Email:
to = None
from = None
subject = None
content = None
@classmethod
def create_and_send(cls, to, from, subject, content):
cls(to=to, from=from, subject=subject, content=content).send()
This won't be a benefit to every class you create, but it's often a better way of approaching use cases where you don't need the class to hang around longer than needed to perform some action.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up