How to Define and Use Static Methods in Python

Using Static Methods in Python
  • Author Avatar
    Written by:

    Nathan Rosidi

A practical guide to defining and applying static methods in Python using Walmart’s Black Friday dataset to segment customer spending.

Static methods are like Python class methods, but there are differences. You don’t need an object (self) or a class (cls). So, when you use them, your code will be more concise and cleaner compared to other methods, such as instance and class.

This article will explore how static methods work in Python, the difference between static methods and the others, using a real-life data project from Walmart, but first, let’s start with the fundamentals of it.

What is a Static Method in Python?

Unlike normal methods, a static method doesn’t care about the object or its data. It is more similar to regular functions, but they are defined inside a class.

When you write methods in Python inside a class, you typically use “self”. That is how the technique knows which object it is working with. An object here refers to a specific instance created from a class.

How to Define a Static Method in Python?

Let’s define both these classes and see them in code.

class Person:
    def __init__(self, name):
        self.name = name         

    def greet(self):             
        return f"Hello, I’m {self.name}!"

    @staticmethod
    def say_hello():             
        return "Hello, everyone!"


We used two methods to see the differences. Let’s run this code.

p = Person("Alice")
print(p.greet())         
print(Person.say_hello())  

Here is the output.

How to Define a Static Method in Python

Who’s Who?

  • Person("Alice") → Creates an object.
  • self → A special keyword that refers to that specific object.
  • greet() → A regular method that uses the object’s data via self.
  • say_hello() → Static method
    • No need to create an object or call it on an instance.

Python Static Method Example - Fixed Discount

You’re working in sales and need to apply a discount. It’s always the same. Doesn’t matter which product or who the customer is.

A static method makes perfect sense here since the logic is simple and doesn’t rely on any instance or class-level context.

Let’s write a class that applies this discount with no extra conditions.

And in the code below, we assume the original price is $100 and the discount rate is 20%.

class PriceTool:
    @staticmethod
    def apply_discount(price, rate):
        return price * (1 - rate)

original_price = 100
discount_rate  = 0.2

discounted = PriceTool.apply_discount(original_price, discount_rate)

print(f"The price before discount: ${original_price}")
print(f"The price after  discount: ${discounted}")


Here we inserted this method with two different inputs: the price and discount rate, and it returns the reduced amount. Because it doesn’t depend on any object data, we made it static to avoid using self and to keep the class cleaner.

Using a Python Static Method in a Real Walmart Data Project

In this data project, Walmart wants us to analyze the customer purchase behavior.

Using a Python Static Method in a Real Data Project

Link to this project: https://platform.stratascratch.com/data-projects/black-friday-purchases

Exploring the Walmart Dataset Before Using Python Static Methods

Before using static methods, let’s load the dataset and preview the head of the dataset.

import pandas as pd
df = pd.read_csv("/Users/learnai/Strata/walmart_data.csv")
df.head()

Here is the output.

Python Static Method Example

The dataset includes columns that list customers’ demographics, product details, and the exact purchase amount for every sale.

Segmenting Customer Purchases Using Static Methods in Python

We have loaded the Walmart Black Friday dataset and understood its structure. Next step, let’s segment the purchase behaviour.

First, we’ll group each purchase as Low, Medium, or High based on how much was spent.

That way, we can check if women or men spend more on Black Friday. Instead of repeating the same logic everywhere, we’ll put it inside a static method so we can reuse it easily.

Step 1- Creating a Python Static Method for Purchase Segmentation

In step 1, we will create a class named “PurchaseSegmenter” with a static method.

It takes a purchase amount and segments it into three different categories:

  • “High Spender”
  • “Medium Spender”
  • “Low Spender”

class PurchaseSegmenter:
    @staticmethod
    def categorize(amount):
        if amount < 5000:
            return "Low Spender"
        elif amount < 15000:
            return "Medium Spender"
        else:
            return "High Spender"

Step 2- Applying Your Static Method in Python to the Full Dataset

In step 2, we will apply this method to label every transaction in the dataset and save the results to the “Spending_Level” column by creating it.

df['Spending_Level'] = df['Purchase'].apply(PurchaseSegmenter.categorize)

spending_counts = df['Spending_Level'].value_counts()
spending_counts


Here is the output.

Python Static Method Example


The majority of purchases are in the Medium Spender group, with High and Low coming next.

Step 3- Analyzing Gender Differences Using a Static Method in Python

We used our static method to tag every purchase as Low, Medium, or High Spender. Next, let’s compare how these spending levels are distributed between male and female customers.

Here is the full code to group the data and plot the result.

spending_by_gender = df.groupby(['Gender', 'Spending_Level']).size().unstack().fillna(0)

spending_by_gender_percent = spending_by_gender.div(spending_by_gender.sum(axis=1), axis=0) * 100

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 5))
spending_by_gender_percent.T.plot(kind='bar', ax=ax)

ax.set_title("Spending Level Distribution by Gender (%)", fontsize=14)
ax.set_ylabel("Percentage")
ax.set_xlabel("Spending Level")
plt.xticks(rotation=0)
plt.legend(title="Gender")
plt.tight_layout()
plt.show()


Here is the output.

Python Static Method Example

As we can see;

  • Women make up a larger share of the medium spenders.
  • Men have a noticeably higher share among high spenders
  • Both genders have nearly equal proportions of low spenders, but women take the lead slightly here.

Static Method vs Class Method vs Instance Method

Static Method vs Class Method vs Instance Method in Python

In Python, you can have three types of methods inside a class:

  • Static Method
  • Class Method
  • Instance Method

Let’s define each method and compare them.

Instance Method

This is the most common method type. It takes self as the first argument and works with the specific object you create from the class. Check the code below.

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hi, I'm {self.name}!"

p = Person("Alice")
print(p.greet())  


Here is the output.

Python Static Method Example

Use this when your method needs to read or change the object-level data.

Class Method

A class method takes “cls” as a first parameter. Instead of working with a specific object, it works with the class. Check the code below.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_birth_year(cls, name, year):
        return cls(name, 2025 - year)

p = Person.from_birth_year("Bob", 1990)
print(p.age)  


Here is the output.

 Python Static Method Example


Use it when you want to create new objects or change values that belong to the entire class, not one object.

Static Method

A static method doesn’t take self or cls. It doesn’t care about the class or the object; it just does a job. Check the code below.

class MathTools:
    @staticmethod
    def add(x, y):
        return x + y

print(MathTools.add(5, 3)) 


Here is the output.

Python Static Method Example


Use it when the logic is related to the class but doesn’t need access to its data.

Conclusion

In this article, we have explored static methods and how to use them. To do that, we used a real business question and a real-world dataset.

Overall, using a static method gave us three key benefits: it kept our logic reusable, separated from object data, and tightly organized inside a relevant class.

Share

Become a data expert. Subscribe to our newsletter.