What is the difference between @staticmethod and @classmethod in Python?
Quick answer
A classmethod receives the class as its first argument (cls) and can create or configure instances, while a staticmethod receives no automatic argument and is just a function placed inside the class namespace.
Use @classmethod for alternative constructors such as Date.from_string(...), and because it uses cls, it works correctly for subclasses. Use @staticmethod for a utility function that is related to the class but needs neither the instance nor the class. An ordinary method receives self, the instance.
class User:
def __init__(self, name):
self.name = name
@classmethod
def from_email(cls, email):
return cls(email.split("@")[0])
@staticmethod
def is_valid_email(email):
return "@" in email