Python2.7 学习体会 @classmethod @staticmethod @property 之间的关系

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python2.7 学习体会 @classmethod @staticmethod @property 之间的关系相关的知识,希望对你有一定的参考价值。

先来一个实例场景,然后测试,比较,不懂的话到网上找资料:
#!/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


初步测试结果:

1、@property  装饰器后面的函数,在实例调用中不能加(),不然会出现错误:TypeError: ‘str‘ object is not callable

2、正常的方法,在实例调用中如果不加() ,就是不运行函数,而只是返回函数(方法)的地址:

3、@staticmethod 装饰器后面的函数,在实例调用中必须加对像参数,不然会提示:TypeError: statictime() takes exactly 1 argument (0 given)

4、@classmethod 我的初步理解:是对类,进行重新的定义初始化。

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

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

明天继续….

























































以上是关于Python2.7 学习体会 @classmethod @staticmethod @property 之间的关系的主要内容,如果未能解决你的问题,请参考以下文章

Python2.7 学习体会 @classmethod @staticmethod @property 之间的关系二

python2.7 与 selenium 2 学习

python2.7 函数的参数学习

python语言特性-------python2.7教程学习廖雪峰版

python2.7提示编码出错

python基础-------python2.7教程学习廖雪峰版