Skip to main content

Python Tutorial 8.5 - Class & Static Methods

Welcome to the “Class & Static Methods” tutorial!


Overview

  • @classmethod: method receives the class (cls) as the first argument.
  • @staticmethod: method receives no implicit first argument.

Example

class Pizza:
    base_price = 10

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

    @classmethod
    def with_extra_cheese(cls):
        return cls(["cheese"])

    @staticmethod
    def diet_info():
        return "Contains carbs and fats."

print(Pizza.base_price)                  # 10
cheesy = Pizza.with_extra_cheese()
print(cheesy.toppings)                   # ['cheese']
print(Pizza.diet_info())                 # Contains carbs and fats.

Key Takeaways

  • Use @classmethod to access/modify class state.
  • Use @staticmethod for utility functions related to class.

Happy coding!

Comments