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

A Better Pizza Interface With Class Methods

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!

Comments & Discussion

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'])

Become a Member to join the conversation.