Python - @property method changes properties

Keywords: Python Attribute

@property

  • @property is a built-in decorator. It works the same way as ordinary decorators, except that the returned function is not a function, but a class object
  • @Property is responsible for turning a method into a property to be called to ensure necessary checks on parameters.
  • Property has three decorators: setter, getter, and deleter. When the property has only getter method, it is read-only property. Otherwise, it is read-write property.

Define a class:

class Student(object):
     def __init__(self,score):
         self.__score = score      ## __Score translated into student score
    
     # Allow external code to get score
     def get_score(self):
         print('%s'%self.__score)
         return self.__score

In the above example, when binding the attribute, the attribute is exposed directly, which results in that it can be modified at will, but there is no verification limit for the modification of the score.
In order to limit the scope of attributes, such as score, you can set the score through a set_score() method, and then get the score through a get_score().
For example:

class Student(object):
     def get_score(self):
         return self.score 
         
     def set_score(self,value):
        if not isinstance(value,int):         # Determine the type of input character first
            raise ValueError('score must be an integer')
        if value <0 or value >100:          # Input int data, judge the input range
            raise ValueError('score must between 0 -100 ')
        self.score = value

Commissioning:

>>> s = Student()            # s=Student(60) is not required because there is no init method
>>> s.set_score (60)
>>> s.get_score()
60
>>> s.set_score(101)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in set_score
ValueError: score must between 0 -100

So, is it possible to check parameters and access and judge variables of a class in a simple way like properties?
Do you remember that decorator can dynamically add functions to functions? For class methods, decorators work just as well.

Rules of use:

  • Read only property: only getter method, add @ property before method;
  • Readable and writable properties: there are getter and setter methods. Use @ property name. Setter on setter methods.

For example:

class Student(object):
   # score: readable and writable properties, getter and setter methods

   # To change a getter method into a property, just add @ property
   @property
   def score(self):
       return self._score

   # Create another decorator, @ score.setter, which is responsible for changing a setter method into a property assignment
   @score.setter
   def score(self,value):
       if not isinstance(value,int):
            raise ValueError('score must be an integer ! ')
       if value<0 or value>100:
           raise ValueError ('score must between 0 - 100 ! ')
       self.score = value

   # Define read-only property, only getter method
   @property
   def age(self):
        return self._age

❤ thanks for watching, keep on updating...
Let's go with a compliment

Posted by p.persia69 on Thu, 05 Dec 2019 21:07:52 -0800