Class Method4:07 with Kenneth Love
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.
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 = 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.
You need to sign up for Treehouse in order to download course files.Sign up