Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey there it's done and today I want to talk about the difference between class methods static methods and plain or regular instance methods in Python kind of demystify some of differences between them when you would use each what are some of the common scenarios and how you can use them to actually make your code cleaner and more maintainable and easier to work with in the future okay so let's jump right in I want to make this really hands-on and kind of work from a simple example that I can use to show you the difference so I created this class I called my class just a really simple example and it's got a couple of different method types on it so the first one is just called method or the method is called method and it's just a plain instance method you can see here it takes one argument the self argument which points to the object instance and that means within method we can actually modify or read attributes on the object instance and when you compare that to a class method so I just called this one class method and then use the class method decorator to actually mark it as a class method you can see here that the class method only has access to this class parameter or this class argument it doesn't have have a self argument so this means a class method it can only access the the class itself or the object representing the class because while everything is an object in Python but the key difference is that when I create an instance of my class and then call class method on it it won't be able to to actually access the self object right so it can only access attributes that actually exist on the class itself and not on the instance now with static method again the approach is really similar you just you know define a regular method and in market with the add static method decorator what you can see here is that it doesn't take any arguments at all so it has no access to the class or the object instance at all so it's completely separate from that it's really just a way to namespace your methods so now you know I know this this is a very very theoretical at this point and it's going to become much more clear when we actually try and do some experimentation with the stuff some hands-on work so the first thing I want to show you here is that when I create an object instance base on this class I can actually call any of these method types on that object so I can call a plane method and it kind of structured these these methods in a way that they return a string that kind of explains what's going on right so when I call object dot method we can see here that well we call the instance method and we have this self object pointing to an instance off of my class now I can do the same thing with class method and I want to call this you can see here that again we're calling this class method method and this time we also have access to this class object now the difference here is that with the instance method we actually had access to the object instance right so this was an instance off a my 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 a class method and static method on an object instance this is going to work it doesn't really make a difference so again when you call static method 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 my class and I'm not creating an instance of this class and I can go in say class method for example this is going to work fine I can also go ahead and say call call the the static method it's 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 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 right why 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 really powerful concept or a really powerful tool for you to structure your code in a way that makes the most sense okay so this is what I came up with the classical pizza example for teaching object-oriented programming so what I've done here is I defined this really simple pizza class it's got a constructor takes you know some bold arbitrary ingredients object we're just going to assume in some kind of lists or container with these ingredients and it also put a wrapper on it so we can nicely format it as a string and in here if you're wondering what that is so that is the new format strings in Python three six which are really awesome so I really encourage you encourage you to try that out could just use regular format strings of course so okay so so basically what I did here I created is pizza class and now we can use it to create pizza objects right and so if I'm not mistaken that's a margarita my wife's Italian you'd probably kick my ass if I got that wrong but I think that's a margarita well what you've seen here is that we can create these pizza objects but as we create more and more complicated pizzas hem like a prosciutto or something I don't know maybe we need some mushrooms on that as well right and and you can already tell I'm struggling with the naming here right I can create all create all these wonderful pizzas here but I need to remember all of these ingredients so now it wouldn't be too much of a stretch to actually have like solved this problem with a static method okay so I wanted to make it a little bit easier for us to create new pizza objects without having to remember all these ingredients and so a really good way to structure this in my opinion is to actually use class methods to have different factory functions for the different types of pizza you can create and I'm going to show you how this works in a minute now so what I'm going to do here is I'm going to define a margarita class method here and then that's just gonna create a new instance of the class and we just type that out here so what i'm doing here is whenever this margarita method is called and we can call it on just a pizza class we don't actually need a real pizza pizza instance i'm just going to call i'm going to create an instance off a pizza or you know whatever class is named like the nice thing here is that I don't have to refer to the name up here so I can keep that name just in one place and whenever I updated I don't have to worry about changing the rest of the code but it's it's just going to use the class objects just going to call this init init method here and it's going to create a new pizza with these ingredients and so this is kind of a really maintainable way to do these factory functions so I could also have a prosciutto I didn't actually look the spelling up for this right so if any italians are watching this then let me know if I if I screw this up so here we actually want cheese I guess that would be mozarella right you're not cheese but whatever it's it's a kind of cheese anyway this is about cheese this is about a Python so okay so I'm creating and creating a different kind of pizza here and now when I when I finish defining this class I can actually say hey I want a margarita and that returns a new pizza object right it could have also called this make margarita or sore new margarita or something like that right just to kind of have a better naming scheme but the same thing is going to work with the prosciutto and I feel like this is a really good use for these class methods if you have classes with complicated constructors you know that take a lot of argument and you want to provide a simplified interface for your users then I think using a class method in this fashion can be really beneficial and it's just going to make the API a little bit easier for people to work with so this is one example of where I would use a static method and of course you could always argue that you know maybe there should be a separate function yada yada yada but I think in some cases this could really work well if you if you structure your your classes that way up next when to use static methods so it's a little bit hard to come up with a really simple example here but you know I'm gonna keep stretching the pizza the pizza thing here so okay so this is what I came up with basically a static method doesn't have access to the class or the object instance at all right and now that's a pretty big limitation but it's also really good signal to well to show that a particular method is is really independent from everything else around it right so for example if I flag this as a static method it's pretty clear that this method it it's probably not gonna change the the object or the class in any way because it's not remit to have access to it I mean sure you know you could probably work around that and it could kind of work with a global variable but in general like it's a pretty good hint that this is a self-contained method which has all kinds of benefits for later testing this thing and just kind of understanding the limitations of this method and so in some cases can really be helpful to make your code easy to maintain in the future because we're really communicating this intent right where you can someone else reading this code can pretty clearly understand that in this case our little circle area function here it's not going to modify the state off this object itself so let me walk you through this example real quick so basically what I've added here well I kind of changed the constructor around a bit so now we've got a radius argument here for the pizza as well forgot to update the rapper but you know doesn't really matter for now and then I added this area function and well I could have just calculated the area of the pizza directly in here but I you know wanted to have a static method in there and so basically what I did there instead of calculating the area directly with an expression here I'm just offloading that to the circle area function and then the circle area function just takes an R which is the radius and uses the classic R squared times x pi formula to calculate the circle area so you know this is honestly like kind of a simplistic example and you usually wouldn't implement it like that but it goes to show the concept and now what happens here is I can instantiate a pizza so for example you know this is a really sad pizza with like 4.5 but we don't have a unit on that right let's say meters a giant pizza cheese only and we're going to create this this object this pizza object and then we're going to call the area function on it and it's going to give us this this result so the way this is calculated is that area actually Forks off the all that work to the circle area function and now the circle area function is actually completely independent and I also used a single underscore to mark it as kind of not part of the public API of this class but kind of an internal implementation detail but nevertheless now the cool thing is that we have this circle area function that is completely independent from the rest of the object can actually modify the object state and this is a pretty good hint for someone else reading the code it also simplifies testing right because when I write my tests for this then I don't have to worry about instantiating a pizza object making sure it doesn't get modified because the circle area helper it can't do that right and so I occasionally use static methods to communicate that intent and to keep my helper functions nice and clean and make sure that they're not modifying the object state all over the place again just a quick recap so we talked about plain methods class methods and static methods when you can call them pretty much all you need to remember is that a regular method needs an object instance to be called on and in a class method it needs a class and it has access to the class and a static method doesn't really have any access to the object or the object instance or the class at all and it's just kind of a way to namespace your functions alright so have fun exploring the the pizza analogy here and building the perfect pizza API in an object-oriented fashion talk to you soon and happy Python II you
Info
Channel: Real Python
Views: 93,805
Rating: undefined out of 5
Keywords: dbader, pytricks, python, python trick, @classmethod, @staticmethod, python method, python programming, clean python, python tutorial, python oop, object-oriented programming, object-oriented python, oop, python class, python classmethod, python staticmethod, python instance methods, python methods, python object, python method types, learn python
Id: PNpt7cFjGsM
Channel Id: undefined
Length: 14min 53sec (893 seconds)
Published: Tue Feb 14 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.