liveBook · Manning

Static method

As explained in Python How-To

A static method is a method defined on a class that does not receive an instance or class reference implicitly and operates independently of instance state.

Need a timestamp for a task-management display, but no particular task supplies the time? A static method keeps that utility on the class without making it depend on an instance. Define it inside the class with @staticmethod. Unlike an instance method, it does not take self as its first parameter. section 8.2.2 section 8.2.1

Listing 8.5 Creating a static method
from datetime import datetime

class Task:
   @staticmethod
   def get_timestamp():
       now = datetime.now()
       timestamp = now.strftime("%b %d %Y, %H:%M")
       return timestamp

This listing defines Task.get_timestamp(). It gets the current time, formats it as a string, and returns the result without reading task attributes. section 8.2.2

Call the utility through the class

Call Task.get_timestamp() and use its result in a display string: refresh_time = f"Data Refreshed: {Task.get_timestamp()}" print(refresh_time) # Data Refreshed: Mar 04 2022, 15:43 The printed time depends on when the call runs. No Task instance is needed. section 8.2.2

Choose the method type by what the operation needs. An instance method uses self to work with a particular object. A class method can use the class, such as its constructor. A static method needs neither. For example, task creation can call a static random-string utility to produce an ID before constructing a task. section 8.2.1 section 14.2.3

@staticmethod
def random_string(length=8):
   """Create a random ASCII string using the specified length

   Args:
       length (int, optional): The desired length for the random 
 string. Defaults to 8.

   Returns:
       str: The random string
   """
   return "".join(choice(ascii_lowercase) for _ in range(length))

The random_string method takes an optional length and returns a string assembled from randomly chosen lowercase ASCII characters. It uses neither self nor cls. section 14.2.3

Class placement is a design choice, not a requirement for every utility. If a function serves a more general purpose than the class does, put it outside the class instead. The date-conversion function pandas.to_datetime, rather than a static method on Series or DataFrame, illustrates that choice. section 8.2.4

How Python How-To covers it

How deep it goes
Explains declaration, class-based calls, and placement trade-offs without examining decorator internals.
Examples
Uses a formatted timestamp and a random lowercase-string generator for task IDs.
What it assumes
Assumes basic class and function syntax while explaining self, the @staticmethod decorator, and class-based calls.
What you can do after
Build it from scratch with @staticmethod, then decide whether a utility belongs on the class or outside it.
How it connects
Contrasts instance methods and class methods, then relates static methods to standalone utility functions.

Also explained in

Compare how 5 books explain static method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.