Phase 7 of 25 · Topic 7.5

Class Methods (@classmethod) vs Static Methods (@staticmethod)

1Concept

1. `@classmethod` receives the class itself (`cls`) as its first parameter, serving as alternative factory constructors; 2. `@staticmethod` receives no implicit first argument, acting as utility functions scoped within the class namespace.

2Architecture Diagram

Instance Method:   def method(self, ...) ---> Bound to instance object
Class Method:      def method(cls, ...)  ---> Bound to Class (Alternative Constructors)
Static Method:     def method(...)       ---> Unbound Utility Function

3Code Example

Python 3.12
import json

class DatabaseConfig:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port

    @classmethod
    def from_json(cls, json_str: str):
        data = json.loads(json_str)
        return cls(data["host"], data["port"])

    @staticmethod
    def is_default_port(port: int) -> bool:
        return port == 5432

config = DatabaseConfig.from_json('{"host": "db.internal.corp", "port": 5432}')
print(f"Database: {config.host}:{config.port}")
print(f"Is Default Postgres Port: {DatabaseConfig.is_default_port(config.port)}")

4Expected Output

Database: db.internal.corp:5432
Is Default Postgres Port: True

5Key Takeaways

  • Use `@classmethod` for factory constructors that properly instantiate subclasses.
  • Use `@staticmethod` for self-contained utility functions that do not touch class or instance state.
  • Standard instance methods receive `self` pointing to the heap instance.