• Python

Command Palette

Search for a command to run...

Python Fundamentals
  • Python Variables
  • Python Operators
  • Python Input-Output
  • Python Type Conversion
Python Data Types
  • Python Strings
  • Python List
  • Python Tuple
  • Python Dictionnaries
  • Python Sets
Python Flow Control
  • Python Conditions
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
Python Functions
  • Python Functions
  • Python Arguments
  • Python Functions Scope
  • Python Recursion
Python Classes
  • Python Classes
  • Python Classes and Static Methods
  • Python Properties
  • Python Decorators
  • Python Error Handling

Create an Account

FREE

Join our community to access more courses.

Create Account

On this page

Understanding @classmethod and @staticmethodWhat Is a Class Method?What Is a Static Method?Instance Methods vs. Class Methods vs. Static MethodsWhen to Use Each TypeCommon Beginner MistakesSummary
      • Pricing
      • Blog

      Python Classes and Static Methods

      Understanding @classmethod and @staticmethod

      In Python, most methods you define inside a class are instance methods. They work with a specific object and can access or change its data. But sometimes, you want a method that works with the class itself, or a method that doesn't need to know about the class or any object at all. This is where class methods and static methods come in.

      This article will show you what they are, how to use them, and when to choose each one.

      What Is a Class Method?

      A class method is a method that works with the class itself, not just with one object. You define a class method using the @classmethod decorator. The first parameter of a class method is always cls, which refers to the class (just like self refers to the object in instance methods).

      Syntax:

      class MyClass:
          @classmethod
          def my_class_method(cls, ...):
              # code that uses cls
              pass
      

      Example: Factory Method Class methods are often used to create objects in different ways (called "factory methods").

      class Dog:
          def __init__(self, name, age):
              self.name = name
              self.age = age
      
          @classmethod
          def from_birth_year(cls, name, birth_year):
              current_year = 2024
              age = current_year - birth_year
              return cls(name, age)
      
      # Create a Dog using the class method
      puppy = Dog.from_birth_year("Buddy", 2022)
      print(puppy.name, puppy.age)  # Output: Buddy 2
      
      • from_birth_year is a class method. It uses cls to create a new Dog object.
      • You can call a class method on the class itself or on an object.

      What Is a Static Method?

      A static method is a method that belongs to a class, but doesn't need to know anything about the class or any object. It's just a function placed inside a class for organization. You define a static method using the @staticmethod decorator. It does not take self or cls as its first parameter.

      Syntax:

      class MyClass:
          @staticmethod
          def my_static_method(...):
              # code that does not use self or cls
              pass
      

      Example: Utility Function Static methods are useful for helper functions related to the class, but that don't need to access or change class or object data.

      class MathTools:
          @staticmethod
          def add(a, b):
              return a + b
      
      print(MathTools.add(3, 5))  # Output: 8
      
      • add is a static method. It doesn't use self or cls.
      • You can call a static method on the class or on an object.

      Instance Methods vs. Class Methods vs. Static Methods

      TypeFirst ParameterCan Access/Modify Instance?Can Access/Modify Class?
      Instance MethodselfYesNo
      Class MethodclsNoYes
      Static Method(none)NoNo
      • Instance methods: Use self, work with object data.
      • Class methods: Use cls, work with class data or create objects.
      • Static methods: No self or cls, just grouped with the class for convenience.

      When to Use Each Type

      • Use an instance method when you need to access or change data on a specific object.
      • Use a class method when you need to access or change class-level data, or when you want to provide alternative ways to create objects.
      • Use a static method for utility functions that make sense to keep with the class, but don't need to access or change any class or object data.

      Common Beginner Mistakes

      • Forgetting to add cls as the first parameter of a class method (or self for instance methods).
      • Trying to use self in a static method (it won't work).
      • Using a static method when you actually need to access class or object data.

      Example of a mistake:

      class Example:
          @classmethod
          def broken(cls):
              print(self)  # ERROR: 'self' is not defined in a class method
      

      Summary

      • Use @classmethod for methods that need the class (cls) as their first parameter.
      • Use @staticmethod for methods that don't need self or cls.
      • Choose the right type based on what your method needs to do.
      • All three can be called on the class or on an object, but only instance methods can access object data.

      Continue Learning

      Python Variables

      Popular

      Getting Started: Understanding Variables in Python In programming, we often need to store informatio

      Python Operators

      For You

      Performing Actions: Understanding Operators in Python In your Python programs, you won't just store

      Python Recursion

      For You

      Solving Problems by Calling Itself: Understanding Recursion Recursion is a programming concept where

      Personalized Recommendations

      Log in to get more relevant recommendations based on your reading history.