SyntaxStudy
Sign Up
Python Class Methods & Static Methods
Python Intermediate 10 min read

Class Methods & Static Methods

Class Methods & Static Methods

Python has three kinds of methods in a class: instance methods (most common), class methods (bound to the class), and static methods (utility functions).

Instance vs Class vs Static

class MyClass:
    class_var = "shared"

    def instance_method(self):
        # has access to self (instance) and cls
        return f"instance: {self.class_var}"

    @classmethod
    def class_method(cls):
        # has access to cls (the class itself), not self
        return f"class: {cls.class_var}"

    @staticmethod
    def static_method(x, y):
        # no self, no cls — just a regular function in the namespace
        return x + y

Class Methods as 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_str):
        y, m, d = map(int, date_str.split("-"))
        return cls(y, m, d)

    @classmethod
    def today(cls):
        from datetime import date
        d = date.today()
        return cls(d.year, d.month, d.day)

d = Date.from_string("2024-05-15")
print(d.year, d.month, d.day)   # 2024 5 15

Static Method Use Case

class MathHelper:
    @staticmethod
    def is_prime(n):
        if n < 2: return False
        return all(n % i != 0 for i in range(2, int(n**0.5)+1))

print(MathHelper.is_prime(17))  # True
Example
class Person:
    _registry = []

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

    @classmethod
    def from_dict(cls, data):
        return cls(data["name"], data["age"])

    @classmethod
    def count(cls):
        return len(cls._registry)

    @staticmethod
    def is_adult(age):
        return age >= 18

p1 = Person("Alice", 30)
p2 = Person.from_dict({"name": "Bob", "age": 17})
print(Person.count())         # 2
print(Person.is_adult(17))    # False
print(Person.is_adult(30))    # True
Pro Tip

Use @classmethod for factory methods (alternative constructors). Use @staticmethod when the method does not need class or instance state — it is just a namespaced function.