1. 程式人生 > >Python2.7 學習體會 @classmethod @staticmethod @property 之間的關系

Python2.7 學習體會 @classmethod @staticmethod @property 之間的關系

bject 關系 rom sel def 實例 rop take 新的

先來一個實例場景,然後測試,比較,不懂的話到網上找資料:
#!/usr/bin/env python

#!/usr/bin/env python

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


@staticmethod
def statictime(self):
return "{year}-{month}-{day}".format(
year = self.year,
month = self.month,
day = self.day
)

@property
def time(self):
return "{year}-{month}-{day}".format(
year = self.year,
month = self.month,
day = self.day
)
@classmethod
def from_string(cls,string):
year,month,day = map(str,string.split(‘-‘))
date = cls(year,month,day)
return date

def showtime(self):
return "{M}/{D}/{Y}".format(
Y = self.year,
M = self.month,
D = self.day
)
print ‘-‘*20
date = Date("2016","11","09")
print ‘date @property ‘,date.time
print ‘date @normal ‘,date.showtime()
print ‘date @staticmethod ‘,date.statictime(date)

print ‘-‘*20
date_string = ‘2017-05-27‘
year,month,day = map(str,date_string.split(‘-‘))
date2 = Date(year,month,day)
print ‘date2 @property ‘,date2.time
print ‘date2 @noraml ‘,date2.showtime()
print ‘date2 @staticmethod ‘,date2.statictime(date2)

print ‘-‘*20
date3 = Date.from_string(date_string)
print ‘date3 @property ‘,date3.time
print ‘date3 @normal ‘,date3.showtime()
print ‘date3 @staticmethod ‘,date3.statictime(date3)

運行結果:
--------------------
date @property 2016-11-09
date @normal 11/09/2016
date @staticmethod 2016-11-09
--------------------
date2 @property 2017-05-27
date2 @noraml 05/27/2017
date2 @staticmethod 2017-05-27
--------------------
date3 @property 2017-05-27
date3 @normal 05/27/2017
date3 @staticmethod 2017-05-27


初步測試結果:

[email protected] 裝飾器後面的函數,在實例調用中不能加(),不然會出現錯誤:TypeError: ‘str‘ object is not callable

2、正常的方法,在實例調用中如果不加() ,就是不運行函數,而只是返回函數(方法)的地址:

[email protected] 裝飾器後面的函數,在實例調用中必須加對像參數,不然會提示:TypeError: statictime() takes exactly 1 argument (0 given)

[email protected] 我的初步理解:是對類,進行重新的定義初始化。

========================================================

實例原型鏈接:http://mp.weixin.qq.com/s/6NJAoFI-DbsNQdA3M1SIMw (非常推薦大家去看看)

明天繼續….

Python2.7 學習體會 @classmethod @staticmethod @property 之間的關系