Fundamentals 4 min read

Understanding Python staticmethod and classmethod with Examples

This article explains Python's staticmethod and classmethod decorators, demonstrates their usage with concrete class examples, and shows how to apply static and class methods in a Date utility class for data validation and conversion.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python staticmethod and classmethod with Examples

In Python, the staticmethod decorator defines a method that does not receive an implicit first argument (neither self nor cls ), allowing it to be called on the class without instantiation.

class C(object):
    @staticmethod
    def f(arg1, arg2, ...):
        ...

The classmethod decorator creates a method that receives the class itself as the first argument ( cls ), enabling access to class attributes and other class methods without needing an instance.

# -*- coding: utf-8 -*-
class A(object):
    _g = 1
    def foo(self, x):
        print('executing foo(%s,%s)' % (self, x))
    @classmethod
    def class_foo(cls, x):
        print('executing class_foo(%s,%s)' % (cls, x))
    @staticmethod
    def static_foo(x):
        print('executing static_foo(%s)' % x)

a = A()
a.foo(1)
a.class_foo(1)
A.class_foo(1)
a.static_foo(1)
A.static_foo('hi')
print(a.foo)
print(a.class_foo)
print(a.static_foo)
# 输出:
# executing foo(<__main__.A object at 0x...>,1)
# executing class_foo(
,1)
# executing class_foo(
,1)
# executing static_foo(1)
# executing static_foo(hi)
#
>
#
>
#

A practical application is shown with a Date class that uses a class method to construct an instance from a string and a static method to validate date strings.

# -*- coding: utf-8 -*-
class Date(object):
    day = 0
    month = 0
    year = 0
    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year
    def display(self):
        return "{0}*{1}*{2}".format(self.day, self.month, self.year)
    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1
    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

date1 = Date('12', '11', '2014')
date2 = Date.from_string('11-13-2014')
print(date1.display())
print(date2.display())
print(date2.is_date_valid('11-13-2014'))
print(Date.is_date_valid('11-13-2014'))
# 输出:
# 12*11*2014
# 11*13*2014
# False
# False

The article concludes with a QR code invitation for readers to share the material and obtain additional automated learning resources.

Programmingfundamentalsclassmethodstaticmethod
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.