前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >为什么 classmethod 比 staticmethod 更受宠?

为什么 classmethod 比 staticmethod 更受宠?

作者头像
somenzz
发布2021-12-27 15:18:25
3910
发布2021-12-27 15:18:25
举报
文章被收录于专栏:Python七号

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

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

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

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

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

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

代码语言:javascript
复制
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 类:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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(),从而生成一个新的实例。从这一点,可以推断出它的使用场景:

  • 当我们需要再次调用构造函数时,也就是创建新的实例对象时
  • 需要不修改现有实例的情况下返回一个新的实例

比如下面的代码:

代码语言:javascript
复制
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 这两个装饰器,来看看他们的本质区别:

代码语言:javascript
复制
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。代码的执行结果如下:

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

最后的话

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-12-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python七号 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、从调用形式上看,二者用法差不多
  • 2、先说说 staticmethod。
  • 3、再说说 classmethod。
  • 4、本质区别
  • 最后的话
相关产品与服务
日志服务
日志服务(Cloud Log Service,CLS)是腾讯云提供的一站式日志服务平台,提供了从日志采集、日志存储到日志检索,图表分析、监控告警、日志投递等多项服务,协助用户通过日志来解决业务运维、服务监控、日志审计等场景问题。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档