zoukankan      html  css  js  c++  java
  • python 面向对象七 property() 函数和@property 装饰符

    一、property引入

    为了使对象的属性不暴露给调用者和进行属性值检查,设置了访问属性的接口函数,使用函数访问属性,并可以在函数内部检查属性。

     1 >>> class Student(object):
     2       def get_score(self):
     3           return self._score
     4       def set_score(self, value):
     5           if not isinstance(value, int):
     6               raise ValueError('score must be an integer!')
     7           if value < 0 or value > 100:
     8               raise ValueError('score must between 0 ~ 100!')
     9           self._score = value
    10 
    11         
    12 >>> s = Student()
    13 >>> s.set_score(10)  
    14 >>> s.get_score()
    15 10

    这样每次访问属性的时候,都要访问函数,相比较之前直接访问属性的方式,变得麻烦了。property可以解决这个麻烦,虽然还是函数,但是可以像属性一样访问。

    二、property装饰器方法:

    >>> class C:
          def __init__(self):
              self.__x = None
          @property
          def x(self):
              return self.__x
          @x.setter
          def x(self,value):
              self.__x=value
          @x.deleter
          def x(self):
              del self.__x
        
    >>> c = C()
    >>> c.x
    >>> c.x = 100
    >>> c.x
    100

    三、property函数方法:

    >>> class C:
            def __init__(self):
                self.__x = None
            def getx(self):
                return self.__x
            def setx(self, value):
                self.__x = value
            def delx(self):
                del self.__x
            x = property(fget=getx,fset=setx,fdel=delx, doc='')
    
        
    >>> c = C()
    >>> c.x = 100
    >>> c.x
    100
    >>> del c.x
    >>> c.x
    Traceback (most recent call last):
      File "<pyshell#64>", line 1, in <module>
        c.x
      File "<pyshell#59>", line 5, in getx
        return self.__x
    AttributeError: 'C' object has no attribute '_C__x'
  • 相关阅读:
    Go源码文件与命令
    K8s控制器
    odoo 在form视图sheet右上角增加按钮
    odoo 常用widget
    odoo tree视图中实现横向滚动条
    可能是智障的高二生活
    千题计划
    闲谈
    线性代数与simplex
    好题集锦
  • 原文地址:https://www.cnblogs.com/gundan/p/8057844.html
Copyright © 2011-2022 走看看