zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    问题 K: 找点
    问题 B: 喷水装置(二)(在c++上运行有错误,提交AC了)
    问题 A: 喷水装置(一)
    问题 Q: 最大的数
    问题 O: 寻找最大数(三)
    96.n-1位数
    问题 K: A/B Problem
    问题 D: 某种序列
    被限制的加法
    1031苹果分级
  • 原文地址:https://www.cnblogs.com/koujiaodahan/p/9043886.html
Copyright © 2011-2022 走看看