I've seen discussions about difference between @classmethod
and @staticmethod
and about that between @staticmethod
and global functions, but I am still confused about the difference between @staticmethod
and sub-function in a function.
Consider this example below (revised from The definitive guide on how to use static, class or abstract methods in Python):
class Pizza(object):
def __init__(self, cheese, vegetables):
self.cheese = cheese
self.vegetables = vegetables
@staticmethod
def mix_ingredients(x, y):
return x + y
def cook(self):
return self.mix_ingredients(self.cheese, self.vegetables)
Why not:
def cook_pizza(cheese, vegetables):
def mix_ingredients(x, y):
return x + y
return mix_ingredients(cheese, vegetables)
In this example, the function I'd ever use is cook
in Pizza
. Let's say there's no any other functions I'd define in Pizza
in the future, i.e. I do only cooking with pizza. Can't I simply define that as one single function cook_pizza
? In this way mix_ingredients
won't be global and won't have name conflicts with other instances either.
Is there any advantages or disadvantages written that as a @staticmethod
in this case? For example, does Pizza(cheese, vegetables).cook()
perform better than cook_pizza(cheese, vegetables)
because the former doesn't need to define mix_ingredients
every time in the process?