• staticmethod classmethod


    类内的方法常见有三种 ,实例方法,类的静态方法,类方法,

    staticmethod无法传入类本身,因此如果在类内需要访问类的任何方法或者属性,需要直接用类名来访问。好处是,这个是通过类访问的静态方法,类的静态方法,调用的时候需要用类名进行调用。这个有个坏处就是如果类名改变了,内部代码也要改。

    classmethod,类方法,也是类访问,可以通过cls,或者self传入类,因此在类方法内访问类的属性或者方法时,直接通过cls或者self直接访问,这样就有个好处,如果类名发生改变,不需要改变内部的代码。

    class Date:
        
        def __init__(self,year,month,day):
            self.year = year
            self.month = month
            self.day = day
        def tomorrow(self):
            self.day +=1
            
        @staticmethod
        def parse_from_string(date_str):
            year,month,day = tuple(date_str.split('-'))
            return Date(int(year),int(month),int(day))
            
        @classmethod
        def from_string(cls,date_str):
            year,month,day = tuple(date_str.split('-'))
            return cls(int(year),int(month),int(day))        
        '''
        @classmethod
        def from_string(self,date_str):
            year,month,day = tuple(date_str.split('-'))
            return self(int(year),int(month),int(day))
        '''
        @staticmethod
        def valid_str(date_str):
            year,month,day = tuple(date_str.split('-'))
            if int(year)>0 and (int(month)<13 and int(month)>0) and (int(day)<=31 and int(day)>0):
                return True
            else:
                return False
            
        def __str__(self):
            return '{year}{month}{day}'.format(year = self.year, month = self.month,day = self.day)
        
    
    if __name__=='__main__':
        new_day = Date(2018,12,20)
        new_day.tomorrow()
        print(new_day)
        
        date_str = '2018-12-20'
    #    year,month,day = tuple(date_str.split('-'))
    #    
    #    print(year,month,day)
    #    
    #    new_day=Date(int(year),int(month),int(day))
    #    print(new_day)
    #    
        #static method
        tmp_day = Date.parse_from_string(date_str)
        print(tmp_day)
        
        tmp_day = Date.from_string(date_str)
        print(tmp_day)
        
        print(Date.valid_str('2018-06-12'))
        
    
  • 相关阅读:
    49. Group Anagrams
    43. Multiply Strings
    22. Generate Parentheses
    17. Letter Combinations of a Phone Number
    8. String to Integer (atoi)
    【转】C#中base关键字的几种用法:base()
    【转】C#中virtual和abstract的区别
    [转]C#中的abstract 类和方法
    【转】C#虚方法virtual详解
    【转】C#中protected用法详解
  • 原文地址:https://www.cnblogs.com/jianyingzhou/p/16298701.html
Copyright © 2020-2023  润新知