Now that you’ve learned about the basic concepts behind instance, class and static methods, the current lesson let’s you run the code you have written to see the actual results of calling the different method types. Furthermore, limits of certain types are revealed.
What Are These Different Method Types Good for in Python?
So, I can call a plain method—and I kind of structured these methods in a way that they return a string that kind of explains what’s going on. All right, so when I call
obj.method(), we can see here that, well, we called the instance method and we had this
self object pointing to an instance of
Now, I can do the same thing with a class method, and now when I call this, you can see here that, again, we’re calling this
.classmethod() method, and this time we also have access to this class object.
Whereas with the class method, we have access to the class itself, but not to any of the objects because the class method doesn’t really care about an object existing. However, you can both call
.staticmethod() on an object instance.
This is going to work—it doesn’t really make a difference. So again, when you call
.staticmethod() here, it’s going to work and it’s going to know which method you want to call, but really, the key difference now is going to be that we can also say, okay,
MyClass—and I’m not creating an instance of this class—and I can go in and say
.classmethod(), for example. This is going to work fine.
And I can also go ahead and call the
.staticmethod(). This is also going to work fine. But of course, when I try and call
.method(), that’s going to fail because we didn’t actually call it with a class instance.
02:01 So, I hope this makes this distinction between regular methods and static and class methods a little bit more clear. Now, of course, the big question is, “Okay, why…why do we need that? Why is that a thing?” And I want to go over some examples here of what you can use these methods for, because I think they’re actually a really powerful concept, or a really powerful tool, for you to structure your code in a way that makes the most sense.
Become a Member to join the conversation.