Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

A Better Pizza Interface With Class Methods

Give Feedback

After building the Pizza class, it’s time to extend it using @classmethods. In this lesson you’ll add class methods for different pizza types, to that you can create your favorite pizza without remembering the ingredients!

seyi bello on Aug. 5, 2019

A static method can also be used to create factory functions. What is the difference between the 2 below:

class Pizza:

    def __init__(self, ingredients):
        self.ingredients = ingredients

    def __repr__(self):
        return f'Pizza({self.ingredients})'

    @classmethod
    def margherita(cls):
        return cls(['cheese', 'tomatoes'])

    @classmethod
    def prosciutto(cls):
        return cls(['cheese', 'tomatoes', 'ham', 'mushrooms'])
class Pizza:

    def __init__(self, ingredients):
        self.ingredients = ingredients

    def __repr__(self):
        return f'Pizza({self.ingredients})'

    @staticmethod
    def margherita():
        return Pizza(['cheese', 'tomatoes'])

    @staticmethod
    def prosciutto():
        return Pizza(['cheese', 'tomatoes', 'ham', 'mushrooms'])

mdroberts on Nov. 15, 2019

Why do you refer to the Pizza factory methods as “Static method” sometimes and “class method” at other times? They are not synonymous as there are “static methods” distinct from “class methods”?

Dan Bader RP Team on Nov. 15, 2019

If you use a staticmethod instead of a classmethod you’ll need to spell out the class name explicitly in the method body:

@staticmethod
def margherita():
    return Pizza(['cheese', 'tomatoes'])

This means if you ever rename the class to something else (e.g. PizzaFlatBread) these methods will break, because Pizza is now undefined.

With a classmethod you can avoid this issue because you’ll get a reference to the class you can use instead of referring to the class name explicitly:

@classmethod
def margherita(cls):
    return cls(['cheese', 'tomatoes'])

In the example above, check out how I’m using cls(...) to create the instance instead of calling Pizza(...) directly :)

Become a Member to join the conversation.