In this lesson, you’ll get an overview of @staticmethod
and @classmethod
decorators. You’ll see how to create these decorators as well as how to invoke the static and class methods associated with a class.
Static Methods vs Class Methods: Overview and Example Code
00:00
We’ll be discussing the @staticmethod
and @classmethod
decorators and their usage in Python. This is often a confusion point for many people coming from other languages, and we’ll be explaining the difference between both and show you a few useful examples of when to use each. As you can see here, we have a class defined called Item
, which has a few class attributes, an .__init__()
which takes a number
, a .static_method()
which simply prints 'This is a static method'
, and we have a .class_method()
that prints 'This is a class method'
and introspects a few of the class attributes. In order to make something a static method, all you need to do is apply the @staticmethod
decorator. Class methods require the first argument in the function that you’re decorating to be cls
(class), so you can introspect the class itself. Next, we’re going to discuss how to invoke static and class methods.
00:51
As you can see here, we have an instance of Item
, which we assigned to i
. We are then able to run the static and class methods on that instance.
01:00 The cool thing about static and class methods is that we can invoke them as well on the class, which is what they’re designed to do. So, as you can see below, they do the exact same thing in both cases, and they both introspect the same exact way.
01:14 So you can choose to run them against either an instance of a particular class or the class itself.
Become a Member to join the conversation.