This lesson covers the differences between @classmethod
s and @staticmethod
s. Unlike @staticmethod
s, @classmethod
s are
aware of the attributes of the class they belong to. You’ll learn that Class Methods can instantiate new objects of that class type and you’ll get to see a real world example of them in use.
What Makes Class Methods Different?
00:00 Next, let’s discuss class methods. As we had shown earlier, class methods can take into account some class information. For example, they’re aware of class attributes and they can also instantiate new objects of that class type.
00:13
As you can see below, the new Integer
class, which has some class attributes, an .__init__()
method, and a class method called .new_number()
. As with all class methods, the class is passed as the first argument, followed by x number of arguments and keyword arguments. In this case, we only have number
. This particular method prints some class attributes and returns a new instance of the Integer
class.
00:41
Just to show you that this isn’t any different from any other particular class—everything works the same, nothing new. An interesting difference is that the fact that this .new_number()
method can return new instances of Integer
. So as you see above, we declared this Integer
class by simply going class
, open brace, some argument which it accepts in its .__init__()
, and close bracket.
01:08
As you can see here in our .new_number()
class method, it has the same pattern, if you will, but this will work for any particular class or subclass of Integer
.
01:18
And in this case, Integer
is being passed, so we then call Integer(number)
, which results in it being the same as Integer
and some number. In this case below, we passed the number 8
, which then is assigned to the new_number
variable, which then prints 8
. And as you can see above here, we ask for .some_class_attribute
, it prints 'So True!'
, and then when we return the instance here to new_number
and ask for the .number
, we get the original number we passed in, which is 8
.
01:48 This is really the power of class methods, and this is oftentimes what you’ll see people use it for, or to store some caching variables in class attributes as you move forward.
01:59 Albeit there are other ways to solve this particular problem, but there may be some restraints where this may be necessary or even useful.
Become a Member to join the conversation.