SyntaxStudy
Sign Up
Python @staticmethod and @classmethod
Python Intermediate 4 min read

@staticmethod and @classmethod

@staticmethod and @classmethod

@staticmethod defines a method with no access to the instance or class. @classmethod receives the class as its first argument and is used for alternative constructors.

Example
class Circle:
    PI = 3.14159

    def __init__(self, radius):
        self.radius = radius

    @staticmethod
    def validate(r):
        return r > 0

    @classmethod
    def unit(cls):
        return cls(1)

c = Circle.unit()
print(c.radius)  # 1
Pro Tip

Use @classmethod for factory methods that create instances.