Difference between @classmethod and @staticmethod in Python
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('-'))
date = cls(day, month, year)
return date
@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
date1 = Date(11, 9, 2012)
date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')
@classmethod
- Cls must be defined as an argument
- In the above code, different instantiation methods are realized with
@classmethod </ code> in the same class Date.
@staticmethod
- No need for obligatory parameters such as cls and self
- Basically, it can be seen as an ordinary function
- Inaccessible to everything inside the class
- The purpose is to clarify the logic