PYTHON Contents

Staticmethod vs Classmethod

Use @staticmethod and @classmethod intentionally: choose based on whether behavior depends on instance state or class-level construction.

On this page

Choosing the Right Method Type

  • instance method: uses self and instance state
  • @classmethod: uses cls, often as alternate constructor
  • @staticmethod: utility scoped to a class, no self/cls

Alternate Constructor

class RetryPolicy:
    def __init__(self, retries: int) -> None:
        self.retries = retries

    @classmethod
    def from_env(cls, env: dict) -> "RetryPolicy":
        value = int(env.get("RETRIES", "2"))
        return cls(retries=value)

Static Utility

class Urls:
    @staticmethod
    def join(base: str, path: str) -> str:
        return base.rstrip("/") + "/" + path.lstrip("/")

Operational Checklist

  • Use @classmethod for factories and alternate constructors.
  • Use @staticmethod sparingly; prefer module-level functions if no class context is needed.
  • Keep method types consistent across similar classes.

Failure Modes

  • Factory confusion: mixing constructors and factories inconsistently complicates usage.
  • Overusing staticmethods: classes become namespaces without clear responsibility.