Skip to main content
Editor

Python @classmethod vs @staticmethod: When to Use Each

Intermediate20 min5 exercises70 XP
0/5 exercises

Imagine a company with three kinds of employees. Regular employees work on their own tasks (they need to know about themselves). Managers can hire new employees for the whole department (they need to know about the department). Utility workers do general tasks like cleaning that don't depend on any specific person or department.

Python methods work the same way. Regular methods operate on a specific object (self). Class methods operate on the class itself (cls). Static methods don't need access to either - they're just helper functions that logically belong to the class.

In this tutorial, you'll learn exactly when and how to use @classmethod and @staticmethod, and the powerful factory method pattern that makes @classmethod so useful.

How Do Regular Instance Methods Work?

Before we learn the new method types, let's quickly recap regular methods. A regular method takes self as its first parameter and can access and modify the object's data.

Regular method recap
class Pizza:
def __init__(self, size, toppings):
self.size = size
self.toppings = toppings
def describe(self): # Regular method: uses self
return f'{self.size}" pizza with {", ".join(self.toppings)}'
pizza = Pizza(12, ['cheese', 'mushroom'])
print(pizza.describe())
Output
12" pizza with cheese, mushroom

The describe() method needs self to access self.size and self.toppings. This is the most common type of method, and it's what you've been writing so far.

What Is @classmethod and How Does It Work?

A class method receives the class itself as its first argument instead of an instance. You mark it with the @classmethod decorator, and by convention the first parameter is called cls (not self).

@classmethod receives the class as cls
class Pizza:
default_size = 12 # Class attribute
def __init__(self, size, toppings):
self.size = size
self.toppings = toppings
@classmethod
def change_default_size(cls, new_size):
cls.default_size = new_size
print(f'Default size changed to {new_size}"')
print(f'Before: {Pizza.default_size}"')
Pizza.change_default_size(14)
print(f'After: {Pizza.default_size}"')
Output
Before: 12"
Default size changed to 14"
After: 14"

Notice that change_default_size uses cls.default_size instead of self.default_size. It modifies the class attribute, which affects all instances - not just one specific pizza.

What Are Factory Methods?

The most powerful use of @classmethod is the factory method pattern. A factory method is an alternative constructor - it gives you a different way to create objects besides calling ClassName() directly.

For example, what if you want to create a Date object from a string like '2024-01-15'? You can't change __init__ to handle both formats cleanly. Instead, you create a factory method.

Factory methods: alternative constructors
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_string):
year, month, day = date_string.split('-')
return cls(int(year), int(month), int(day))
@classmethod
def today_fake(cls):
return cls(2024, 1, 15) # Pretend today is Jan 15
def __str__(self):
return f'{self.year}-{self.month:02d}-{self.day:02d}'
# Three ways to create a Date:
d1 = Date(2024, 3, 20) # Regular constructor
d2 = Date.from_string('2024-07-04') # Factory from string
d3 = Date.today_fake() # Factory for "today"
print(d1)
print(d2)
print(d3)
Output
2024-03-20
2024-07-04
2024-01-15

The key line is return cls(int(year), int(month), int(day)). The factory method parses the string, then uses cls(...) to create a new instance. Using cls instead of Date means this will work correctly even with subclasses.

Temperature factory method
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, f):
return cls((f - 32) * 5 / 9)
def __str__(self):
return f'{self.celsius:.1f}C'
# Create from Celsius directly
t1 = Temperature(100)
print(t1)
# Create from Fahrenheit using factory method
t2 = Temperature.from_fahrenheit(212)
print(t2)
t3 = Temperature.from_fahrenheit(72)
print(t3)
Output
100.0C
100.0C
22.2C

What Is @staticmethod and How Does It Work?

A static method doesn't receive self or cls. It's just a regular function that lives inside a class because it's logically related. It can't access or modify the instance or the class.

@staticmethod: no self, no cls
class MathHelper:
@staticmethod
def is_even(n):
return n % 2 == 0
@staticmethod
def is_positive(n):
return n > 0
@staticmethod
def clamp(value, low, high):
return max(low, min(high, value))
print(MathHelper.is_even(4))
print(MathHelper.is_even(7))
print(MathHelper.is_positive(-3))
print(MathHelper.clamp(15, 0, 10))
Output
True
False
False
10

These methods don't need any data from an instance or the class. They're just utility functions grouped under MathHelper for organization. You call them on the class directly.

Static method as a validator
class Pizza:
def __init__(self, size, toppings):
self.size = size
self.toppings = toppings
@staticmethod
def validate_topping(topping):
valid = ['cheese', 'mushroom', 'pepperoni', 'olive']
return topping.lower() in valid
def add_topping(self, topping):
if self.validate_topping(topping):
self.toppings.append(topping)
return f'Added {topping}'
return f'{topping} is not available'
pizza = Pizza(12, ['cheese'])
print(pizza.add_topping('mushroom'))
print(pizza.add_topping('pineapple'))
print(Pizza.validate_topping('olive'))
Output
Added mushroom
pineapple is not available
True

The validate_topping method doesn't need self or cls - it just checks a topping against a list. Making it a static method signals to other developers that this function is independent of any specific instance.

When Should You Use Each Method Type?

Here's the simple decision guide:

  • Regular method - needs access to the instance (self). This is the default. Use it for reading or changing an object's data.
  • @classmethod - needs access to the class (cls). Use it for factory methods and modifying class-level state.
  • @staticmethod - doesn't need self or cls. Use it for utility functions that logically belong to the class.
  • Ask yourself: does it need self or cls?
    # Needs self? -> Regular method
    def get_area(self):
        return self.width * self.height
    
    # Needs cls? -> @classmethod
    @classmethod
    def from_square(cls, side):
        return cls(side, side)
    Needs neither? -> @staticmethod
    # No self, no cls -> @staticmethod
    @staticmethod
    def is_valid_dimension(value):
        return value > 0
    All three method types in one class
    class User:
    active_users = 0 # Class attribute
    def __init__(self, name, email):
    self.name = name
    self.email = email
    User.active_users += 1
    # Regular method: needs self
    def greet(self):
    return f'Hi, I\'m {self.name}!'
    # Class method: needs cls
    @classmethod
    def from_string(cls, user_string):
    name, email = user_string.split(',')
    return cls(name.strip(), email.strip())
    # Static method: needs neither
    @staticmethod
    def is_valid_email(email):
    return '@' in email and '.' in email
    print(User.is_valid_email('alice@test.com')) # Static
    user = User.from_string('Alice, alice@test.com') # Class method
    print(user.greet()) # Instance method
    print(f'Active users: {User.active_users}')
    Output
    True
    Hi, I'm Alice!
    Active users: 1

    What Are Common Real-World Patterns?

    Let's look at a realistic example. Imagine you're building a configuration system where settings can come from different sources - a dictionary, a JSON string, or default values.

    Config class with multiple factory methods
    import json
    class Config:
    def __init__(self, host, port, debug):
    self.host = host
    self.port = port
    self.debug = debug
    @classmethod
    def from_dict(cls, data):
    return cls(
    data.get('host', 'localhost'),
    data.get('port', 8080),
    data.get('debug', False),
    )
    @classmethod
    def from_json(cls, json_string):
    data = json.loads(json_string)
    return cls.from_dict(data) # Reuse the dict factory!
    @classmethod
    def default(cls):
    return cls('localhost', 8080, False)
    @staticmethod
    def is_valid_port(port):
    return 1 <= port <= 65535
    def __str__(self):
    return f'{self.host}:{self.port} (debug={self.debug})'
    # Multiple ways to create the same thing
    c1 = Config.default()
    c2 = Config.from_dict({'host': '0.0.0.0', 'port': 3000, 'debug': True})
    c3 = Config.from_json('{"host": "api.example.com", "port": 443}')
    print(c1)
    print(c2)
    print(c3)
    print(Config.is_valid_port(3000))
    print(Config.is_valid_port(99999))
    Output
    localhost:8080 (debug=False)
    0.0.0.0:3000 (debug=True)
    api.example.com:443 (debug=False)
    True
    False

    Notice how from_json calls cls.from_dict internally. Factory methods can chain together, keeping each one simple and focused on a single conversion step.

    Here is a quick summary of the three method types side by side:

    Quick reference cheat sheet
    # Regular method: operates on ONE specific object
    # -> def method(self, ...)
    # -> Access self.attribute, self.other_method()
    
    # @classmethod: operates on the CLASS itself
    # -> def method(cls, ...)
    # -> Access cls.class_attribute, cls(...) to create instances
    
    # @staticmethod: independent helper
    # -> def method(...)
    # -> No access to self or cls, just a utility function

    Practice Exercises

    Create a Factory Method
    Write Code

    Create a Person class with name and age attributes. Add a @classmethod called from_birth_year that takes name and birth_year, calculates the age (use 2024 as the current year), and returns a new Person.

    Create a person using Person.from_birth_year('Alice', 2000) and print their name and age on separate lines.

    # Create your Person class here
    Add a Static Validator
    Write Code

    Create a Password class with a value attribute. Add a @staticmethod called is_strong that takes a password string and returns True if it has 8 or more characters, False otherwise.

    Print the result of Password.is_strong('abc') and Password.is_strong('securepass123').

    # Create your Password class here
    Predict the Method Output
    Predict Output

    Read the code and predict the output. Pay attention to which method type each is.

    class Counter:
        count = 0
    
        def __init__(self):
            Counter.count += 1
    
        @classmethod
        def get_count(cls):
            return cls.count
    
        @staticmethod
        def info():
            return 'I count things'
    
    a = Counter()
    b = Counter()
    c = Counter()
    print(Counter.get_count())
    print(Counter.info())
    class Counter:
    count = 0
    def __init__(self):
    Counter.count += 1
    @classmethod
    def get_count(cls):
    return cls.count
    @staticmethod
    def info():
    return 'I count things'
    a = Counter()
    b = Counter()
    c = Counter()
    print(Counter.get_count())
    print(Counter.info())
    Fix the Factory Method
    Fix the Bug

    This Rectangle class has a factory method with two bugs. Fix them so the code prints:

    5 x 5
    class Rectangle:
    def __init__(self, width, height):
    self.width = width
    self.height = height
    def from_square(cls, side):
    return cls(side, side)
    def __str__(self):
    return f'{self.width} x {self.height}'
    square = Rectangle.from_square(5)
    print(square)
    Build a Temperature Converter
    Write Code

    Create a Temperature class that stores temperature in Celsius:

    1. __init__(self, celsius) stores the value

    2. @classmethod from_fahrenheit(cls, f) - creates from Fahrenheit: (f - 32) * 5 / 9

    3. @staticmethod is_freezing(celsius) - returns True if celsius <= 0

    4. to_fahrenheit(self) - returns the Fahrenheit value: self.celsius * 9 / 5 + 32

    Create a temperature using Temperature.from_fahrenheit(32). Print:

  • The celsius value (should be 0.0)
  • The result of to_fahrenheit() (should be 32.0)
  • The result of Temperature.is_freezing(0.0) (should be True)
  • # Build your Temperature class here

    Harder problems

    More problems on this topic: Classes

    Related Tutorials

    Was this tutorial helpful?