成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

為什么 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編程

2015-07-31 16:29:15

DockerJavaLinux

2019-04-24 08:00:00

HTTPSHTTP前端

2020-11-17 09:10:44

裝飾器

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技術棧公眾號

主站蜘蛛池模板: 午夜精品影院 | 欧美自拍一区 | 欧美一级在线观看 | 国产91丝袜在线播放 | 谁有毛片 | 国产精品久久久久一区二区三区 | 免费成人av网站 | 精品综合久久久 | 爱爱视频日本 | 伊人网国产 | 久热精品在线播放 | 久久久久国产精品一区三寸 | 亚洲人成人一区二区在线观看 | 免费午夜视频在线观看 | 人人干免费 | 亚洲高清在线观看 | 在线看亚洲 | 久久久av| 日韩一级免费 | 久久黄网 | 日本成人三级电影 | 一级视频在线免费观看 | 欧美一级毛片免费观看 | 国产高清av免费观看 | 国产成人a亚洲精品 | 亚洲影音| 成人黄色在线 | 先锋影音资源网站 | 成av在线| 国产一区二区电影 | 国产欧美日韩一区二区三区 | 羞羞色在线观看 | 成人免费视频网站在线看 | 国产精品久久久久无码av | 欧美性猛交 | 精品一区二区三区在线观看 | 国产成人精品免费视频大全最热 | 在线观看黄视频 | 人人人人爽 | 最新91在线 | 国产激情视频在线 |