• 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

  • 相关阅读:
    PHP strcmp,strnatcmp,strncmp函数的区别
    PHP echo,print_r(expression),var_dump(expression)区别
    PHP包含文件语句include和require的区别
    PHP魔术变量__METHOD__,__FUNCTION__的区别
    解决margin重叠的问题
    冒牌、选择、插入排序算法
    == 和 === 的区别
    Javascript常见浏览器兼容问题
    浏览器常见兼容性问题汇总
    JS中replace()用法举例
  • 原文地址:https://www.cnblogs.com/koujiaodahan/p/9043886.html
Copyright © 2020-2023  润新知