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、做一個顏色的動態匹配

class ColorTest(object):
    color = "color"
    @classmethod
    def value(self):
        return self.color
    
class Red(ColorTest):
    color = "red"
    
class Green(ColorTest):
    color = "green"

g = Green()
print g.value()
print Green.value()

  其中,基類做一個抽象共性,對於實際的顏色的值需要結合實際的類進行匹配。

2、假設我有一個學生類和一個班級類,想要實現的功能為:

班級類含有類方法:

執行班級人數增加的操作、獲得班級的總人數

學生類繼承自班級類,每實例化一個學生,班級人數都能增加。

最后,我想定義一些學生,然后獲得班級中的總人數。

 

思考:這個問題用類方法做比較合適,因為我實例化的時學生,但是如果我從學生這一個實例中獲得班級總人數是不合理的。

同時,如果想要獲得班級總人數,如果生成一個班級的實例也是沒有必要的。

class ClassTest(object):
    __num = 0
    @classmethod
    def addNum(self):
        self.__num += 1
    @classmethod
    def getNum(self):
        return self.__num
    
    def __new__(self):
        ClassTest.addNum()
        return super(ClassTest,self).__new__(self)
    
class Student(ClassTest):
    def __init__(self):
        self.name = ''
          

a = Student()
b = Student()
ClassTest.getNum()  

  這里我用到魔術函數__new__,主要是為了在創建實例的時候調用人數累加的函數。

類函數可以通過類名以及實例兩種方法調用!

注意:

python2 中,必須總要把一個方法聲明為靜態的,從而能夠不帶一個實例而調用它。

python3 中,如果方法只通過類調用,而不需要通過實例調用的話,不用非要聲明為靜態的。

#!/usr/bin/python
class test:
  def show():
    print ("show")

test.show()

  此時會出現錯誤:

[root@localhost home]# ./test.py
Traceback (most recent call last):
File "./test.py", line 6, in <module>
test.show()
TypeError: unbound method show() must be called with test instance as first argument (got nothing instead)

 

改到python3即可:

#!/usr/bin/python3
class test:
  def show():
    print ("show")

test.show()

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM