staticmethod classmethod

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

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

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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 @   deeplearner_allen  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示