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/

本文来自博客园,作者:BioinformaticsMaster,转载请注明原文链接:https://www.cnblogs.com/koujiaodahan/p/9043886.html

原文地址:https://www.cnblogs.com/koujiaodahan/p/9043886.html