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

    假设有这么一个 class

    class Date(object):
    
        def __init__(self, day=0, month=0, year=0):
            self.day = day
            self.month = month
            self.year = year
    

    现在要把一个字符串 11-09-2012 作为变量,方法一:

    string_date = '20-16-2017'
    day, month, year = map(int, string_date.split('-'))
    date1 = Date(day, month, year)
    print date1.day
    

    但是每次初始化一个 classinstance 都要重复操作一次。所以,方法二:

    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
    date2 = Date.from_string('20-06-2017')
    print date2.day
    

    staticmethodclassmethod类似,区别在于不接收变量。例如在 class 加入一个判断:

        @staticmethod
        def is_date_valid(date_as_string_for_check):
            day, month, year = map(int, date_as_string_for_check.split('-'))
            return day <= 31 and month <= 12 and year <= 3999
    
    date2 = Date.from_string('20-06-2017')
    is_date = Date.is_date_valid('20-06-2017')
    print date2.day
    print is_date
    

    另外一个使用了 classmethodstaticmethod的例子:

    class Employee:
        num_of_emps = 0
        raise_amount = 1.04
    
        def __init__(self, first, last, pay):
    
            self.first = first
            self.last = last
            self.pay = pay
            self.email = first + '.' + last + '@company.com'
    
            Employee.num_of_emps += 1
    
        def fullname(self):
            return '{} {}'.format(self.first, self.last)
    
        def apply_raise(self):
            self.pay = int(self.pay * self.raise_amount)
    
        @classmethod
        def set_raise_amt(cls, amount):
            cls.raise_amount = amount
    
        @classmethod
        def from_string(cls, emp_str):
            first, last, pay = emp_str.split('-')
            return cls(first, last, pay)
    
        @staticmethod
        def is_workday(day):
            if day.weekday() == 5 or day.weekday() == 6:
                return False
            return True
    
    
    emp_1 = Employee('Corey', 'Schafer', 50000)
    emp_2 = Employee('Test', 'User', 60000)
    
    import datetime
    my_date = datetime.date(2016, 7, 11)
    
    print(Employee.is_workday(my_date))
    

    另外一个例子:

    class Letter:
        def __init__(self, pattern=None):
            self.pattern = pattern
          
        def __iter__(self):
            yield from self.pattern
          
        def __str__(self):
            output = []
            for blip in self:
                if blip == '.':
                    output.append('dot')
                else:
                    output.append('dash')
            return '-'.join(output)
        
        @classmethod
        def from_string(cls, pattern_string):
    #        new_input_str = []
            pattern_string = pattern_string.split('-')
            for i, _ in enumerate(pattern_string):
                if _ == 'dot':
                    pattern_string[i] = '.'
                elif _ == 'dash':
                    pattern_string[i] = '_'
            cls = cls(pattern_string)
            return cls
    #        for _ in input_str:
    #            if _ == 'dot':
    #                new_input_str.append('.')
    #            elif _ == 'dash':
    #                new_input_str.append('_')
        
    
    class S(Letter):
        def __init__(self):
             pattern = ['.', '.', '.']
             super().__init__(pattern)
    
  • 相关阅读:
    【转载】Java嵌入Pig编程
    【转载】Pig语法进阶
    【转载】各种SQL在PIG中实现
    机器学习简易入门(三)
    机器学习简易入门(一)
    在Centos7上安装漏洞扫描软件Nessus
    R简易入门(二)
    R简易入门(一)
    Mysql主从同步(复制)
    Mysql备份与恢复
  • 原文地址:https://www.cnblogs.com/yaos/p/7056022.html
Copyright © 2011-2022 走看看