| [ Web Proxy ] |
| Viewing: https://www.pythonbyexample.dev/examples/classmethods-and-staticmethods | [Back] [Original] |
Classes
An instance method receives the instance as self and reads its state. This is the default and the right shape when the work depends on a particular object's data.
Source
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def display(self):
return f"{self.year}-{self.month:02d}-{self.day:02d}"
today = Date(2026, 5, 9)
print(today.display())Output
2026-05-09@classmethod makes the method receive the class itself as cls. The canonical use is an alternate constructor that parses some other input format and calls cls(...). Because cls is the actual class, subclasses calling the same method get an instance of their own type.
Source
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, text):
year, month, day = (int(part) for part in text.split("-"))
return cls(year, month, day)
later = Date.from_string("2026-12-31")
print(later.year, later.month, later.day)Output
2026 12 31@staticmethod strips the implicit first argument. The function lives on the class for namespacing like Date.is_leap_year(2024) but does not touch any instance or class state.
Source
class Date:
@staticmethod
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(Date.is_leap_year(2024))
print(Date.is_leap_year(2025))Output
True
FalseSide by side: instance methods receive the instance, classmethods receive the class, staticmethods receive nothing. Classmethods and staticmethods can be called on either the class or an instance.
Source
class Demo:
def instance_method(self):
return type(self).__name__
@classmethod
def class_method(cls):
return cls.__name__
@staticmethod
def static_method():
return "no receiver"
print(Demo().instance_method())
print(Demo.class_method())
print(Demo.static_method())Output
Demo
Demo
no receiverNotes
@classmethod for alternate constructors and class-level operations that respect subclassing.@staticmethod only when a function is truly independent of instance and class state but still belongs in the class's namespace.2026-05-09
2026-12-31
True
False
Demo
Demo
no receiver
Execution time appears here after you run the example.
| Web Proxy Viewer | New URL | Original Page |