Example of @property in Python

  • 2021-06-28 09:25:40
  • OfStack

This article provides an example of how @property is understood and used in Python.Share it for your reference, as follows:

Looking back at Dogbook, there are two lines below when you see the definition of the User table


  @property
  def password(self):
    raise AttributeError('password is not a readable attribute')
  @password.setter
  def password(self, password):
    self.password_hash = generate_password_hash(password)

Then review the use of this property

When we define a database field class, we often need to make some restrictions on its class properties. 1 is generally written in the get and set methods. In python, how can we write less code, and elegantly implement the desired restrictions and reduce errors? We need to do so now. @property Bright, Barabara energy.....

Examples with code are easier to understand, such as the definition of a student report form


class Student(object):
  def get_score(self):
    return self._score
  def set_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

We need to call it this way:


>>> s = Student()
>>> s.set_score(60) # ok!
>>> s.get_score()
60
>>> s.set_score(9999)
Traceback (most recent call last):
 ...
ValueError: score must between 0 ~ 100!

But for convenience and time saving, we don't want to write s.set_score(9999) Ah, write directly s.score = 9999 Isn't it faster, adding methods to restrict calls doesn't make them more cumbersome? @property Come and help...


class Student(object):
  @property
  def score(self):
    return self._score
  @score.setter
  def score(self,value):
    if not isinstance(value, int):
      raise ValueError(' Scores must be integers ')
    if value < 0 or value > 100:
      raise ValueError(' Score must 0-100 Between ')
    self._score = value

Look at the code above to see that the get Method to property only needs to be added @property Decorators will do, at this time @property Create another Ornament by itself @score.setter , responsible for set The method changes to assigning values to attributes, and when we're done, it's both controllable and convenient to call


>>> s = Student()
>>> s.score = 60 # OK , actually converted to s.set_score(60)
>>> s.score # OK , actually converted to s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
 ...
ValueError: score must between 0 ~ 100!

More information about Python can be found in this site's topics: Python Data Structure and Algorithms Tutorial, Python Socket Programming Skills Summary, Python Function Usage Skills Summary, Python String Operation Skills Summary, and Python Introduction and Advanced Classic Tutorial.

I hope that the description in this paper will be helpful to everyone's Python program design.


Related articles: