为什么 classmethod 比 staticmethod 更受宠?

我们知道,classmethod 和 staticmethod 都可以作为函数的装饰器,都可用于不涉及类的成员变量的方法,但是你查一下 Python 标准库就会知道 classmethod 使用的次数(1052)要远远多于 staticmethod(539),这是为什么呢?

95e911ec28302a4de152389f2440f516.png

这就要从 staticmethod 和 classmethod 的区别说起。

1、从调用形式上看,二者用法差不多

先说下什么是类,什么是实例,比如说 a = A(),那么 A 就是类,a 就是实例。

从定义形式上看,clasmethod 的第一个参数是 cls,代表类本身,普通方法的第一个参数是 self,代表实例本身,staticmethod 的参数和普通函数没有区别。

从调用形式上看,staticmethod 和 classmethod 都支持类直接调用和实例调用。

class MyClass:
    def method(self):
        """
        Instance methods need a class instance and
        can access the instance through `self`.
        """
        return 'instance method called', self

    @classmethod
    def classmethod(cls):
        """
        Class methods don't need a class instance.
        They can't access the instance (self) but
        they have access to the class itself via `cls`.
        """
        return 'class method called', cls

    @staticmethod
    def staticmethod():
        """
        Static methods don't have access to `cls` or `self`.
        They work like regular functions but belong to
        the class's namespace.
        """
        return 'static method called'

# All methods types can be
# called on a class instance:
>>> obj = MyClass()
>>> obj.method()
('instance method called', <MyClass instance at 0x1019381b8>)
>>> obj.classmethod()
('class method called', <class MyClass at 0x101a2f4c8>)
>>> obj.staticmethod()
'static method called'

# Calling instance methods fails
# if we only have the class object:
>>> MyClass.classmethod()
('class method called', <class MyClass at 0x101a2f4c8>)
>>> MyClass.staticmethod()
'static method called'

2、先说说 staticmethod。

如果一个类的函数上面加上了 staticmethod,通常就表示这个函数的计算不涉及类的变量,不需要类的实例化就可以使用,也就是说该函数和这个类的关系不是很近,换句话说,使用 staticmethod 装饰的函数,也可以定义在类的外面。我有时候会纠结到底放在类里面使用 staticmethod,还是放在 utils.py 中单独写一个函数?比如下面的 Calendar 类:

class Calendar:
    def __init__(self):
        self.events = []

    def add_event(self, event):
        self.events.append(event)

    @staticmethod
    def is_weekend(dt:datetime):
        return dt.weekday() > 4

if __name__ == '__main__':
    print(Calendar.is_weekend(datetime(2021,12,27)))
    #output: False

里面的函数 is_weekend 用来判断某一天是否是周末,就可以定义在 Calendar 的外面作为公共方法,这样在使用该函数时就不需要再加上 Calendar 这个类名。

但是有些情况最好定义在类的里面,那就是这个函数离开了类的上下文,就不知道该怎么调用了,比如说下面这个类,用来判断矩阵是否可以相乘,更易读的调用形式是 Matrix.can_multiply:

from dataclasses import dataclass
@dataclass
class Matrix:
    shape: tuple[int, int] # python3.9 之后支持这种类型声明的写法

    @staticmethod
    def can_multiply(a, b):
        n, m = a.shape
        k, l = b.shape
        return m == k

3、再说说 classmethod。

首先我们从 clasmethod 的形式上来理解,它的第一个参数是 cls,代表类本身,也就是说,我们可以在 classmethod 函数里面调用类的构造函数 cls(),从而生成一个新的实例。从这一点,可以推断出它的使用场景:

  • 当我们需要再次调用构造函数时,也就是创建新的实例对象时

  • 需要不修改现有实例的情况下返回一个新的实例

比如下面的代码:

class Stream:

    def extend(self, other):
        # modify self using other
        ...

    @classmethod
    def from_file(cls, file):
        ...

    @classmethod
    def concatenate(cls, *streams):
        s = cls()
        for stream in streams:
            s.extend(stream)
        return s

steam = Steam()

当我们调用 steam.extend 函数时候会修改 steam 本身,而调用 concatenate 时会返回一个新的实例对象,而不会修改 steam 本身。

4、本质区别

我们可以尝试自己实现一下 classmethod 和 staticmethod 这两个装饰器,来看看他们的本质区别:

class StaticMethod:
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner):
        return self.func

    def __call__(self, *args, **kwargs):  # New in Python 3.10
        return self.func(*args, **kwargs)


class ClassMethod:
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner):
        return self.func.__get__(owner, type(owner))

class A:
    def normal(self, *args, **kwargs):
        print(f"normal({self=}, {args=}, {kwargs=})")

    @staticmethod
    def f1(*args, **kwargs):
        print(f"f1({args=}, {kwargs=})")

    @StaticMethod
    def f2(*args, **kwargs):
        print(f"f2({args=}, {kwargs=})")

    @classmethod
    def g1(cls, *args, **kwargs):
        print(f"g1({cls=}, {args=}, {kwargs=})")

    @ClassMethod
    def g2(cls, *args, **kwargs):
        print(f"g2({cls=}, {args=}, {kwargs=})")


def staticmethod_example():
    A.f1()
    A.f2()

    A().f1()
    A().f2()

    print(f'{A.f1=}')
    print(f'{A.f2=}')

    print(A().f1)
    print(A().f2)

    print(f'{type(A.f1)=}')
    print(f'{type(A.f2)=}')


def main():
    A.f1()
    A.f2()

    A().f1()
    A().f2()

    A.g1()
    A.g2()

    A().g1()
    A().g2()

    print(f'{A.f1=}')
    print(f'{A.f2=}')

    print(f'{A().f1=}')
    print(f'{A().f2=}')

    print(f'{type(A.f1)=}')
    print(f'{type(A.f2)=}')


    print(f'{A.g1=}')
    print(f'{A.g2=}')

    print(f'{A().g1=}')
    print(f'{A().g2=}')

    print(f'{type(A.g1)=}')
    print(f'{type(A.g2)=}')

if __name__ == "__main__":
 main()

上面的类 StaticMethod 的作用相当于装饰器 staticmethod,类ClassMethod 相当于装饰器 classmethod。代码的执行结果如下:

86d9bd9ed7764ec5b4b0f9a80e824313.png

可以看出,StaticMethod 和 ClassMethod 的作用和标准库的效果是一样的,也可以看出 classmethod 和 staticmethod 的区别就在于 classmethod 带有类的信息,可以调用类的构造函数,在编程中具有更好的扩展性。

最后的话

回答本文最初的问题,为什么 classmethod 更受标准库的宠爱?是因为 classmethod 可以取代 staticmethod 的作用,而反过来却不行。也就是说凡是使用 staticmethod 的地方,把 staticmethod 换成 classmethod,然后把函数增加第一个参数 cls,后面调用的代码可以不变,反过来却不行,也就是说 classmethod 的兼容性更好。

另一方面,classmethod 可以在内部再次调用类的构造函数,可以不修改现有实例生成新的实例,具有更强的灵活性和可扩展性,因此更受宠爱,当然这只是我的拙见,如果你有不同的想法,可以留言讨论哈。

如果有帮助,还请点赞、在看、转发、关注支持,感谢阅读。

关注公众号后,回复「送书」抽两本《代码大全2》,就这两天了不要错过哦。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值