1. 程式人生 > 其它 >python中的靜態函式與類函式區別與聯絡

python中的靜態函式與類函式區別與聯絡

靜態方法和類方法在python2.2中被引用,經典類和新式類都可以使用。同時,一對內建函式:staticmethod和classmethod被引入,用來轉化類中某一方法為這兩種方法之一。

靜態方法:

靜態方法是類中的函式,不需要例項。靜態方法主要是用來存放邏輯性的程式碼,主要是一些邏輯屬於類,但是和類本身沒有互動,即在靜態方法中,不會涉及到類中的方法和屬性的操作。可以理解為將靜態方法存在此類的名稱空間中。事實上,在python引入靜態方法之前,通常是在全域性名稱空間中建立函式。

例子:

譬如,我想定義一個關於時間操作的類,其中有一個獲得當前時間的函式。


import time class TimeTest(object): def __init__(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second @staticmethod def showTime(): return time.strftime("%H:%M:%S", time.localtime()) print(TimeTest.showTime()) t= TimeTest(2,10,10) nowTime= t.showTime() print(nowTime)

  

 如上,使用靜態函式,既可以將獲得時間的函式功能與例項解綁,我想獲得當前時間的字串時,並不一定需要例項化物件,此時更像是一種名稱空間。

我們可以在類外面寫一個簡單的方法來做這些,但是這樣做就擴散了類程式碼的關係到類定義的外面,這樣寫就會導致以後程式碼維護的困難。

靜態函式可以通過類名以及例項兩種方法呼叫

類方法:

類方法是將類本身作為物件進行操作的方法。他和靜態方法的區別在於:不管這個方式是從例項呼叫還是從類呼叫,它都用第一個引數把類傳遞過來

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner/12179325#12179325

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

應用:

1、做一個顏色的動態匹配

原文連結:https://www.cnblogs.com/pinking/p/7944376.html 對原文的print稍有修改