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'))
    

 

posted @ 2022-05-22 22:11  caoeryingzi  阅读(30)  评论(0编辑  收藏  举报