@staticmethod、@classmethod和@property 装饰器

staticmethod

class in_two_out_two_sum(object):

    a = 0
    b = 0

    def __init__(self, a = 0, b = 0):
        self.a = a
        self.b = b

    def res(self):
        print self.sum(self.a,self.b)

    @staticmethod
    def sum(a,b):
        return a + b

a = in_two_out_two_sum(3,2)
a.res()

静态方法 sum()属于class in_two_out_two_sum() 但是class in_two_out_two_sum()的类和实例都可以调用这个方法。


@classmethod

简单来说 类的方法就叫类方法.
与staticmethod 差不多 但是可以传入一个当前类作为参数

class print_your_birthday(object):

    year = 0
    month = 0
    date = 0

    def __init__(self, year = 0, month = 0, date = 0):
        self.year = year
        self.month = month
        self.date = date  

    @classmethod
    def format_birthday(cls, not_format_date):

        year, month, date = map(int, not_format_date.split('-'))

        birthday = cls(year, month, date)
        return birthday

    def print_birth(self):
        print 'year:' , self.year
        print 'month:' , self.month
        print 'date:' , self.date

birth = print_your_birthday(2017,11,12)
birth.print_birth()

birth = print_your_birthday.format_birthday('2017-11-12')
birth.print_birth()
"""
outputs:
year: 2017
month: 11
date: 12
year: 2017
month: 11
date: 12
"""
class C(object):
    num = 1

    def funA(self):
        print 'A'

    @classmethod
    def funB(cls):
        print 'B'
        print cls.num
        cls().funA()

C.funB()
"""
outputs:
B
1
A
"""

@staticmethod 和 @classmethod 混用

class C(object):
    num = 1

    def funA(self):
        print 'A'

    @classmethod
    def funB(cls):
        cls.out('B')
        cls.out(cls.num)
        cls().funA()
    
    @staticmethod
    def out(strs):
        print strs

C.funB()
"""
outputs:
B
1
A
"""

@property

property 函数用作装饰器可以很方便的创建只读属性
注意 getter 、setter和deleter 里的命名不能与本类的名字相同,不然会产生无限递归调用。

class C(object):
    def __init__(self):
        self._x = None
 
    def getx(self):
        return self._x
 
    def setx(self, value):
        self._x = value
 
    def delx(self):
        del self._x
 
    x = property(getx, setx, delx, "I'm the 'x' property.")

你可能感兴趣的:(@staticmethod、@classmethod和@property 装饰器)