property/staticmethod/classmethod

首先他们三个都是python面对对象的装饰器

1 property

1.1 作用:将类方法变成属性

1.2 示例:

class Foo(object):

    def __init__(self):
        self._name = 'www'
        self._age = 12

    # 可读可写方法,但写的时候要满足 t_property.setter
    @property
    def t_property(self):
        return self._name

    @t_property.setter
    def t_property(self, value):
        if isinstance(value, str):
            self._name = value
        print 'change only in string type'
        return

    # 只读方法
    @property
    def t2_property(self):
        return self._age

 result:

f  = Foo(12)
f.t_property   # 把方法当成属性调用
f.t_property = 13  # 更改私有属性

f.t2_property = 10  # 报错,因为没有将私有方法定义为可写 

2 staticmethod 和 classmethod

2.1 作用:只能被类调用的方法

2.2 相同点:都是被类调用的方法

2.3. 不同点:classmethod 中有 cls(也就是可以调用类属性等操作),而 staticmethod 没有 cls

class Foo(object):

    name = 'www'

    @staticmethod
    def t_staticmethod():
        return 'im test staticmethod'

    @classmethod
    def t_classmethod(cls):
        print cls.name
        return 'im test classmethod'
原文地址:https://www.cnblogs.com/fuzzier/p/7940240.html