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




