为什么 Classmethod 比 Staticmethod 更受宠?

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

[[442137]]

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

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

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

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

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

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

  1. class MyClass: 
  2.     def method(self): 
  3.         ""
  4.         Instance methods need a class instance and 
  5.         can access the instance through `self`. 
  6.         ""
  7.         return 'instance method called', self 
  8.  
  9.     @classmethod 
  10.     def classmethod(cls): 
  11.         ""
  12.         Class methods don't need a class instance. 
  13.         They can't access the instance (self) but 
  14.         they have access to the class itself via `cls`. 
  15.         ""
  16.         return 'class method called', cls 
  17.  
  18.     @staticmethod 
  19.     def staticmethod(): 
  20.         ""
  21.         Static methods don't have access to `cls` or `self`. 
  22.         They work like regular functions but belong to 
  23.         the class's namespace. 
  24.         ""
  25.         return 'static method called' 
  26.  
  27. All methods types can be 
  28. # called on a class instance: 
  29. >>> obj = MyClass() 
  30. >>> obj.method() 
  31. ('instance method called', <MyClass instance at 0x1019381b8>) 
  32. >>> obj.classmethod() 
  33. ('class method called', <class MyClass at 0x101a2f4c8>) 
  34. >>> obj.staticmethod() 
  35. 'static method called' 
  36.  
  37. # Calling instance methods fails 
  38. # if we only have the class object: 
  39. >>> MyClass.classmethod() 
  40. ('class method called', <class MyClass at 0x101a2f4c8>) 
  41. >>> MyClass.staticmethod() 
  42. 'static method called' 

2、先说说 staticmethod。

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

  1. class Calendar: 
  2.     def __init__(self): 
  3.         self.events = [] 
  4.  
  5.     def add_event(self, event): 
  6.         self.events.append(event) 
  7.  
  8.     @staticmethod 
  9.     def is_weekend(dt:datetime): 
  10.         return dt.weekday() > 4 
  11.  
  12. if __name__ == '__main__'
  13.     print(Calendar.is_weekend(datetime(2021,12,27))) 
  14.     #outputFalse 

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

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

  1. from dataclasses import dataclass 
  2. @dataclass 
  3. class Matrix: 
  4.     shape: tuple[intint] # python3.9 之后支持这种类型声明的写法 
  5.  
  6.     @staticmethod 
  7.     def can_multiply(a, b): 
  8.         n, m = a.shape 
  9.         k, l = b.shape 
  10.         return m == k 

3、再说说 classmethod。

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

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

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

比如下面的代码:

  1. class Stream: 
  2.  
  3.     def extend(self, other): 
  4.         # modify self using other 
  5.         ... 
  6.  
  7.     @classmethod 
  8.     def from_file(cls, file): 
  9.         ... 
  10.  
  11.     @classmethod 
  12.     def concatenate(cls, *streams): 
  13.         s = cls() 
  14.         for stream in streams: 
  15.             s.extend(stream) 
  16.         return s 
  17.  
  18. steam = Steam() 

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

4、本质区别

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

  1. class StaticMethod: 
  2.     def __init__(self, func): 
  3.         self.func = func 
  4.  
  5.     def __get__(self, instance, owner): 
  6.         return self.func 
  7.  
  8.     def __call__(self, *args, **kwargs):  # New in Python 3.10 
  9.         return self.func(*args, **kwargs) 
  10.  
  11.  
  12. class ClassMethod: 
  13.     def __init__(self, func): 
  14.         self.func = func 
  15.  
  16.     def __get__(self, instance, owner): 
  17.         return self.func.__get__(owner, type(owner)) 
  18.  
  19. class A: 
  20.     def normal(self, *args, **kwargs): 
  21.         print(f"normal({self=}, {args=}, {kwargs=})"
  22.  
  23.     @staticmethod 
  24.     def f1(*args, **kwargs): 
  25.         print(f"f1({args=}, {kwargs=})"
  26.  
  27.     @StaticMethod 
  28.     def f2(*args, **kwargs): 
  29.         print(f"f2({args=}, {kwargs=})"
  30.  
  31.     @classmethod 
  32.     def g1(cls, *args, **kwargs): 
  33.         print(f"g1({cls=}, {args=}, {kwargs=})"
  34.  
  35.     @ClassMethod 
  36.     def g2(cls, *args, **kwargs): 
  37.         print(f"g2({cls=}, {args=}, {kwargs=})"
  38.  
  39.  
  40. def staticmethod_example(): 
  41.     A.f1() 
  42.     A.f2() 
  43.  
  44.     A().f1() 
  45.     A().f2() 
  46.  
  47.     print(f'{A.f1=}'
  48.     print(f'{A.f2=}'
  49.  
  50.     print(A().f1) 
  51.     print(A().f2) 
  52.  
  53.     print(f'{type(A.f1)=}'
  54.     print(f'{type(A.f2)=}'
  55.  
  56.  
  57. def main(): 
  58.     A.f1() 
  59.     A.f2() 
  60.  
  61.     A().f1() 
  62.     A().f2() 
  63.  
  64.     A.g1() 
  65.     A.g2() 
  66.  
  67.     A().g1() 
  68.     A().g2() 
  69.  
  70.     print(f'{A.f1=}'
  71.     print(f'{A.f2=}'
  72.  
  73.     print(f'{A().f1=}'
  74.     print(f'{A().f2=}'
  75.  
  76.     print(f'{type(A.f1)=}'
  77.     print(f'{type(A.f2)=}'
  78.  
  79.  
  80.     print(f'{A.g1=}'
  81.     print(f'{A.g2=}'
  82.  
  83.     print(f'{A().g1=}'
  84.     print(f'{A().g2=}'
  85.  
  86.     print(f'{type(A.g1)=}'
  87.     print(f'{type(A.g2)=}'
  88.  
  89. if __name__ == "__main__"
  90.  main() 

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

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

最后的话

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

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

本文转载自微信公众号「Python七号」,可以通过以下二维码关注。转载本文请联系Python七号公众号。

 

责任编辑:武晓燕 来源: Python七号
相关推荐

2017-07-20 16:02:27

Python编程

2020-11-17 09:10:44

装饰器

2015-07-31 16:29:15

DockerJavaLinux

2019-04-24 08:00:00

HTTPSHTTP前端

2018-06-21 08:50:53

2024-02-05 22:51:49

AGIRustPython

2015-01-06 09:37:58

2018-10-17 11:30:02

前后端代码接口

2020-12-02 09:14:47

Apache批处理流式数据

2011-12-07 20:37:42

iOSAndroid谷歌

2020-02-16 20:43:49

Python数据科学R

2023-01-10 15:00:44

2019-02-24 22:05:12

JuliaPython语言

2018-10-07 05:08:11

2021-01-13 10:51:08

PromissetTimeout(函数

2022-11-10 15:32:29

2020-09-08 16:00:58

数据库RedisMemcached

2019-11-29 09:29:12

互联网SRE运维

2016-12-14 12:02:01

StormHadoop大数据

2017-02-14 14:20:02

StormHadoop
点赞
收藏

51CTO技术栈公众号