@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).
下面是一个来自于stackoverflow的例子,其中的@classmethod作为另类的构造函数,而@staticmethod用作类相关的辅助方法。
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
@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
if __name__ == "__main__":
date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')
print(is_date)
本文地址已经归档到github,您可以访问下面的链接获得。
代码地址
如果觉得本文对您有帮助,敬请点赞。