zoukankan      html  css  js  c++  java
  • classmethod 和 staticmethod

    我一般很少用到。

    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!

    完。

  • 相关阅读:
    HTML5新特性之文件和二进制数据的操作
    HTML5本地存储之IndexedDB
    HTML5新标签之Canvas
    HTML5 Canvas实战之烟花效果
    Asp.NET core/net 5接口返回实体含有long/int64的属性序列后最后几位变为0的解决
    Aero for WTL application
    C++WTL基于MCI的音频播放器源码
    c++ 深拷贝,浅拷贝,赋值操作的调用情况
    发布一个生成按钮图片的工具 c#写的
    贴图:CImage VS Bitmap
  • 原文地址:https://www.cnblogs.com/gaowengang/p/9224592.html
Copyright © 2011-2022 走看看