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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值