classmethod 和 staticmethod

时间:2022-12-03 17:02:54

我一般很少用到。

Talk is cheap, show you the code.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
# To explain how to use classmethod and staticmethod.
############################################################################### # ordinary class
class Date(object): def __init__(self, year=0, month=0, day=0):
self.year = year
self.month = month
self.day = day def __str__(self):
return '/'.join([str(x) for x in (self.year, self.month, self.day)]) # class with classmethod and staticmethod
class DateV2(object): def __init__(self, year=0, month=0, day=0):
self.year = year
self.month = month
self.day = day def __str__(self):
return '/'.join([str(x) for x in (self.year, self.month, self.day)]) @classmethod
def from_string(cls, str_): # Note, `cls`
y, m, d = str_.split('-')
date = cls(y, m, d)
return date @staticmethod
def data_str_valid(str_): # note no `self` or `cls`
y, m, d = str_.split('-')
return (0 < int(y) <= 9999) and (1 <= int(m) <= 12) and (1 <= int(d) <= 31) # derive
class DateV3(DateV2):
pass if __name__ == '__main__': ################################################### test ordinary class
d = Date(2018, 6, 25)
print d y, m, d = "2018-6-25".split('-')
d2 = Date(y, m, d)
print d2 ################################################## test class with classmethod and staticmethod
d3 = DateV2(2018, 6, 25)
print d3 #dstr = '2018-6-25'
dstr = '2018-6-32'
if DateV2.data_str_valid(dstr):
d4 = DateV2.from_string('2018-6-25')
print d4
else:
print 'dstr invalid!' ################################################# test derive
d5 = DateV3.from_string('2018-6-6')
print d5 #dstr = '2018-6-25'
dstr = '2018-6-32'
if DateV3.data_str_valid(dstr):
d6 = DateV3.from_string('2018-6-25')
print d6
else:
print 'dstr invalid!'

Output is,

2018/6/25
2018/6/25
2018/6/25
dstr invalid!
2018/6/6
dstr invalid!

完。