python @property 将类的方法转化为属性读取并赋值

@property 将类方法转化为类属性调用。

########################################################################
class Person(object):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, first_name, last_name):
        """Constructor"""
        self.first_name = first_name
        self.last_name = last_name

    #----------------------------------------------------------------------
    @property
    def full_name(self):
        """
        Return the full name
        """
        return "%s %s" % (self.first_name, self.last_name)

>>> person = Person("Mike", "Driscoll")
>>> person.full_name
'Mike Driscoll'
>>> person.first_name
'Mike'
>>> person.full_name = "Jackalope"  # 此时类方法转化的属性只读,不可赋值
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
AttributeError: can't set attribute

 

>>> person.first_name = "Dan"
>>> person.full_name
'Dan Driscoll'

要赋值就需要setter:

from decimal import Decimal

########################################################################
class Fees(object):
""""""

#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self._fee = None

#----------------------------------------------------------------------
@property
def fee(self):
"""
The fee property - the getter
"""
return self._fee

#----------------------------------------------------------------------
@fee.setter
def fee(self, value):
"""
The setter of the fee property
"""
if isinstance(value, str):
    self._fee = Decimal(value)
elif isinstance(value, Decimal):
    self._fee = value

#----------------------------------------------------------------------
if __name__ == "__main__":
    f = Fees()

>>> f = Fees()
>>> f.fee = "1"

重要参考:http://python.jobbole.com/80955/

转载于:https://www.cnblogs.com/koujiaodahan/p/9043886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值