classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
date2 = Date.from_string('11-09-2012')
classmethod的第一個(gè)參數(shù)就是類本身,
cls is an object that holds class itself, not an instance of the class.
不管這個(gè)方式是從實(shí)例調(diào)用還是從類調(diào)用,它都用第一個(gè)參數(shù)把類傳遞過來(lái).
staticmethod可以沒有任何參數(shù)
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
# usage:
is_date = Date.is_date_valid('11-09-2012')
就像調(diào)用一個(gè)普通函數(shù)一樣,只不過這個(gè)函數(shù)在Date類里.
上面兩個(gè)例子都沒有創(chuàng)建實(shí)例就使用類里面的方法,這應(yīng)該就是使用這兩個(gè)裝飾器的優(yōu)勢(shì)吧.
參考: stackoverflow