码迷,mamicode.com
首页 > 编程语言 > 详细

Python类方法、静态方法和实例方法的区别

时间:2018-06-28 21:58:46      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:str   nbsp   tom   date   __str__   需要   row   object   stat   

 1 #-*- encoding:utf-8 -*-
 2 
 3 class Date(object):
 4     def __init__(self, year, month, day):
 5         self.year = year
 6         self.month = month
 7         self.day = day
 8 
 9     #实例方法
10     def tomorrow(self):
11         self.day +=1
12 
13     #静态方法(缺点:需要写入固定的类方法名Date)
14     @staticmethod
15     def parse_from_string(data_str):
16         year, month, day = tuple(data_str.split("-"))
17         return Date(int(year), int(month), int(day))
18 
19     #类方法(传入cls类本身,无需固定类方法名Date)
20     @classmethod
21     def parse_string(cls, data_str):
22         year, month, day = tuple(data_str.split("-"))
23         return cls(int(year), int(month), int(day))
24 
25     def __str__(self):
26         return "{year}/{month}/{day}".format(year=self.year, month=self.month, day=self.day)
27 
28 if __name__ == "__main__":
29     data_str = "2018-6-29"
30     #调用实例方法
31     data = Date(2018,6,29)
32     data.tomorrow()
33     print(data)
34     #调用静态方法
35     print(Date.parse_from_string(data_str))
36     #调用类方法
37     print(Date.parse_string(data_str))

 

Python类方法、静态方法和实例方法的区别

标签:str   nbsp   tom   date   __str__   需要   row   object   stat   

原文地址:https://www.cnblogs.com/Phantom3389/p/9240860.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!