自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

為什么 Classmethod 比 Staticmethod 更受寵?

開發(fā) 前端
我們知道,classmethod 和 staticmethod 都可以作為函數(shù)的裝飾器,都可用于不涉及類的成員變量的方法,但是你查一下 Python 標(biāo)準(zhǔn)庫(kù)就會(huì)知道 classmethod 使用的次數(shù)(1052)要遠(yuǎn)遠(yuǎn)多于 staticmethod(539),這是為什么呢?

[[442137]]

 我們知道,classmethod 和 staticmethod 都可以作為函數(shù)的裝飾器,都可用于不涉及類的成員變量的方法,但是你查一下 Python 標(biāo)準(zhǔn)庫(kù)就會(huì)知道 classmethod 使用的次數(shù)(1052)要遠(yuǎn)遠(yuǎn)多于 staticmethod(539),這是為什么呢?

這就要從 staticmethod 和 classmethod 的區(qū)別說(shuō)起。

1、從調(diào)用形式上看,二者用法差不多

先說(shuō)下什么是類,什么是實(shí)例,比如說(shuō) a = A(),那么 A 就是類,a 就是實(shí)例。

從定義形式上看,clasmethod 的第一個(gè)參數(shù)是 cls,代表類本身,普通方法的第一個(gè)參數(shù)是 self,代表實(shí)例本身,staticmethod 的參數(shù)和普通函數(shù)沒有區(qū)別。

從調(diào)用形式上看,staticmethod 和 classmethod 都支持類直接調(diào)用和實(shí)例調(diào)用。

  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、先說(shuō)說(shuō) staticmethod。

如果一個(gè)類的函數(shù)上面加上了 staticmethod,通常就表示這個(gè)函數(shù)的計(jì)算不涉及類的變量,不需要類的實(shí)例化就可以使用,也就是說(shuō)該函數(shù)和這個(gè)類的關(guān)系不是很近,換句話說(shuō),使用 staticmethod 裝飾的函數(shù),也可以定義在類的外面。我有時(shí)候會(huì)糾結(jié)到底放在類里面使用 staticmethod,還是放在 utils.py 中單獨(dú)寫一個(gè)函數(shù)?比如下面的 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 

里面的函數(shù) is_weekend 用來(lái)判斷某一天是否是周末,就可以定義在 Calendar 的外面作為公共方法,這樣在使用該函數(shù)時(shí)就不需要再加上 Calendar 這個(gè)類名。

但是有些情況最好定義在類的里面,那就是這個(gè)函數(shù)離開了類的上下文,就不知道該怎么調(diào)用了,比如說(shuō)下面這個(gè)類,用來(lái)判斷矩陣是否可以相乘,更易讀的調(diào)用形式是 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、再說(shuō)說(shuō) classmethod。

首先我們從 clasmethod 的形式上來(lái)理解,它的第一個(gè)參數(shù)是 cls,代表類本身,也就是說(shuō),我們可以在 classmethod 函數(shù)里面調(diào)用類的構(gòu)造函數(shù) cls(),從而生成一個(gè)新的實(shí)例。從這一點(diǎn),可以推斷出它的使用場(chǎng)景:

當(dāng)我們需要再次調(diào)用構(gòu)造函數(shù)時(shí),也就是創(chuàng)建新的實(shí)例對(duì)象時(shí)

需要不修改現(xiàn)有實(shí)例的情況下返回一個(gè)新的實(shí)例

比如下面的代碼:

  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() 

當(dāng)我們調(diào)用 steam.extend 函數(shù)時(shí)候會(huì)修改 steam 本身,而調(diào)用 concatenate 時(shí)會(huì)返回一個(gè)新的實(shí)例對(duì)象,而不會(huì)修改 steam 本身。

4、本質(zhì)區(qū)別

我們可以嘗試自己實(shí)現(xiàn)一下 classmethod 和 staticmethod 這兩個(gè)裝飾器,來(lái)看看他們的本質(zhì)區(qū)別:

  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 的作用相當(dāng)于裝飾器 staticmethod,類ClassMethod 相當(dāng)于裝飾器 classmethod。代碼的執(zhí)行結(jié)果如下:

可以看出,StaticMethod 和 ClassMethod 的作用和標(biāo)準(zhǔn)庫(kù)的效果是一樣的,也可以看出 classmethod 和 staticmethod 的區(qū)別就在于 classmethod 帶有類的信息,可以調(diào)用類的構(gòu)造函數(shù),在編程中具有更好的擴(kuò)展性。

最后的話

回答本文最初的問(wèn)題,為什么 classmethod 更受標(biāo)準(zhǔn)庫(kù)的寵愛?是因?yàn)?classmethod 可以取代 staticmethod 的作用,而反過(guò)來(lái)卻不行。也就是說(shuō)凡是使用 staticmethod 的地方,把 staticmethod 換成 classmethod,然后把函數(shù)增加第一個(gè)參數(shù) cls,后面調(diào)用的代碼可以不變,反過(guò)來(lái)卻不行,也就是說(shuō) classmethod 的兼容性更好。

另一方面,classmethod 可以在內(nèi)部再次調(diào)用類的構(gòu)造函數(shù),可以不修改現(xiàn)有實(shí)例生成新的實(shí)例,具有更強(qiáng)的靈活性和可擴(kuò)展性,因此更受寵愛,當(dāng)然這只是我的拙見,如果你有不同的想法,可以留言討論哈。

本文轉(zhuǎn)載自微信公眾號(hào)「Python七號(hào)」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系Python七號(hào)公眾號(hào)。

 

責(zé)任編輯:武曉燕 來(lái)源: Python七號(hào)
相關(guān)推薦

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批處理流式數(shù)據(jù)

2011-12-07 20:37:42

iOSAndroid谷歌

2020-02-16 20:43:49

Python數(shù)據(jù)科學(xué)R

2023-01-10 15:00:44

2019-02-24 22:05:12

JuliaPython語(yǔ)言

2018-10-07 05:08:11

2021-01-13 10:51:08

PromissetTimeout(函數(shù)

2022-11-10 15:32:29

2020-09-08 16:00:58

數(shù)據(jù)庫(kù)RedisMemcached

2019-11-29 09:29:12

互聯(lián)網(wǎng)SRE運(yùn)維

2016-12-14 12:02:01

StormHadoop大數(shù)據(jù)

2017-02-14 14:20:02

StormHadoop
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)