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

More Pizza and When to Use Static Methods

Now that you have learned when to use class methods, the question arises when to use static methods. The current lesson shows you an example, where you could make use of a @staticmethod. Furthermore, the code used in this lesson is provided below, so that you can copy and paste it to try it out yourself.

>>>
>>> import math
>>> 
>>> class Pizza:
...     def __init__(self, radius, ingredients):
...         self.ingredients = ingredients
...         self.radius = radius
...
...     def __repr__(self):
...         return f"Pizza({self.ingredients})"
...
...     def area(self):
...         return self._circle_area(self.radius)
...
...     @staticmethod
...     def _circle_area(r):
...         return r ** 2 * math.pi
...
>>> 
>>> Pizza(4.5, ["cheese"])
Pizza(['cheese'])
>>> 
>>> Pizza(4.5, ["cheese"]).area()
63.61725123519331

Comments & Discussion

prashant23 on July 9, 2019

Thanks for the nice tutorial. So,the static method can be considered to write certain helper functions?

EKELENNOROM on July 13, 2019

The code doesn’t work for python 3.6 and 3.7

Dan Bader RP Team on July 15, 2019

@EKELENNOROM: What’s the error message you’re seeing? Works just fine here on my end (3.6 and 3.7), see below:

→ bpython
bpython version 0.18 on top of Python 3.7.3 /Users/dbader/.pyenv/versions/3.7.3/bin/python3.7
>>> import math
>>>
>>> class Pizza:
...     def __init__(self, radius, ingredients):
...         self.ingredients = ingredients
...         self.radius = radius
...     def __repr__(self):
...         return f"Pizza({self.ingredients})"
...     def area(self):
...         return self._circle_area(self.radius)
...     @staticmethod
...     def _circle_area(r):
...         return r ** 2 * math.pi
...
>>>
>>> Pizza(4.5, ["cheese"])
Pizza(['cheese'])
>>>
>>> Pizza(4.5, ["cheese"]).area()
63.61725123519331

Azian on July 31, 2019

The code runs fine for me on Python 3.7.4.

Become a Member to join the conversation.