python object-oriented seven property() function and @ property decorator

1, property introduction

In order to keep the properties of the object from being exposed to the caller and check the property value, the interface function to access the property is set, and the property can be accessed by using the function, and the property can be checked inside the function.

 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

In this way, each time you access a property, you need to access a function. Compared with the way you directly access a property before, it becomes troublesome. Property can solve this problem. Although it is still a function, it can be accessed like a property.

2, property decorator method:

>>> 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

3, property function method:

>>> 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'

Tags: Python Attribute

Posted on Fri, 08 May 2020 11:37:31 -0400 by Nik