After building the
Pizza class, it’s time to extend it using
In this lesson you’ll add class methods for different pizza types, to that you can create your favorite pizza without remembering the ingredients!
A Better Pizza Interface With Class Methods
After building the
Okay. So, I wanted to make it a little bit easier for us to create new
Pizza objects without having to remember all of these ingredients. 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. I’m going to show you how this works in a minute now.
and let me just type that out here. What I’m doing here is whenever this
.margherita() method is called—and we can call it on just a
Pizza class, we don’t actually need a real
Pizza instance—I’m just going to create an instance of a
Pizza or whatever the 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 update it I don’t have to worry about changing the rest of the code, but it’s just going to call this
.__init__() method, here, and it’s going to create a new
Pizza with these ingredients.
So here, we actually want a cheese—I guess it would be
'mozzarella', right, and not
'cheese', but whatever—it’s a kind of cheese. Anyway, this isn’t about cheese—this is about Python. So, okay. I’m creating a different kind of pizza here, and now when I finish defining this class, I can actually say, “Hey, I want a Margherita,” and that returns a new
Pizza object, right?
02:19 I feel like this is a really good use for these class methods. If you have classes with complicated constructors that take a lot of arguments 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.
02:40 So, this is one example of where I would use a static method. I mean, of course, you could always argue that maybe this should be a separate function, yada yada yada, but I think in some cases this could really work well if you structure your classes that way.
Become a Member to join the conversation.