美文网首页
python @classmethod @staticmetho

python @classmethod @staticmetho

作者: 橙姜 | 来源:发表于2018-05-11 16:33 被阅读0次

@classmethod隐含参数cls, 主要用在需要创建对象的情况,比如多个构造函数的情况,相当于C++重载
@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

date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner

相关文章

网友评论

      本文标题:python @classmethod @staticmetho

      本文链接:https://www.haomeiwen.com/subject/tmofdftx.html