美文网首页python百例
89-OOP之类方法和静态方法

89-OOP之类方法和静态方法

作者: 凯茜的老爸 | 来源:发表于2018-08-02 16:12 被阅读7次

    通过Date创建实例,也可以通过Date.create创建实例

    class Date:
        def __init__(self, year, month, date):
            self.year = year
            self.month = month
            self.date = date
    
        @classmethod  # 类方法,不用创建实例即可调用
        def create(cls, dstr):  # cls表示类本身, class的缩写
            y, m, d = map(int, dstr.split('-'))  # map(int, ['2000', '5', '4'])
            dt = cls(y, m, d)  # 即Date(y, m, d)
            return dt
    
        @staticmethod  # 静态方法,写在类的外面,可以独立成为一个函数,“愣”把它放到类中了
        def is_date_valid(dstr):
            y, m, d = map(int, dstr.split('-'))
            return 1 <= d <= 31 and 1 <= m <=12 and y < 4000
    
    if __name__ == '__main__':
        bith_date = Date(1995, 12, 3)
        print(Date.is_date_valid('2000-5-4'))
        day = Date.create('2000-5-4')
        print(day)
    

    相关文章

      网友评论

        本文标题:89-OOP之类方法和静态方法

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