一 @classmethod介紹
首先classmethod是用在類專用的修飾符。classmethod 修飾符對應的函數不需要實例化,不需要 self 參數,但第一個參數需要是表示自身類的 cls 參數,可以來調用類的屬性,類的方法,實例化對象等。它可以像staticmethod一樣被類對象(記住,是類對象,不是實例)直接調用。又可以像普通類函數一樣調用類內部的函數,因為它的第一個參數是cls,之所以是cls而不是self,是因為cls就是類對象,而非像self表示的類實例。
二 classmethod使用示例:
class Car(object):
def __init__(self, color, type):
self.color = color
self.type = type
@classmethod
def from_tuple(cls, tuple):
return cls(color=tuple[0], type=tuple[1])
def get_color(self):
print(self.color)
def get_type(self):
print(self.type)
if __name__ == '__main__':
car = Car.from_tuple(('red', 'jeep'))
car.get_color()
car.get_type()
輸出結果
red
jeep
三 classmethod的總結
通過以上示例可以得到classmethod的作用有:
1.classmethod修飾的函數使用方式是cls作為第一個參數,不是實例,而是類對象
2.classmethod函數的使用是直接通過A.method調用的形式。
3.classmethod可以返回實例,這樣就可以實現了重載的功能。
4.partial實現了對函數的重載,而classmethod實現了對類的重載
5. 普通的類方法需要通過self參數隱式的傳遞當前類對象的實例。 @classmethod修飾的方法需要通過cls參數傳遞當前類對象。@staticmethod修飾的方法定義與普通函數是一樣的。
閱讀更多 用數說話 的文章