Python's @property

Source: Internet
Author: User

In reading the Python notes of Liao Xuefeng, read the @property characteristics, found a slight deficiency, because they are beginners, hope to benefit more beginners. What is the purpose of @property? Here's a step-by-step description.
  • define class student, with variable name name and Score
    class student (object):       def __init__ (self,name,score):            self.name = name          self.score = score  
In this way, we can modify the member variables of an instance of student outside of the class:
S1 = Student () s1.name = "Lily" S1.score = 9999 # The definition here is unreasonable.
ButThe above definition score is not a parameter check, it means that we can not execute the necessary parameters and error handling。 We can define the corresponding set and get member functions to access the member variable score and perform a parameter check. As shown below:
class Student (object):def __init__ (self,name,score):  self.name = name  Self.score = Scoredef Get_score (self): return self.score  def set_score (self,score):If not isinstance (score, int):  Raise ValueError ("Invalid score!!!")  if score < 0 or score >:  Raise ValueError ("score must be between [0,100]!!!")  Self._score = score  
The code above defines the set and get functions of the score member. (It is possible to modify fractions more often when actually applied) now, we change the parameters of the code is this:
S1 = Student () S1.set_score (9999) #这里会抛出异常
The second method above implements the parameter checking of the set function, but the code that modifies score is changed from simple S1.score = 90 to S1.set_score (90). How can we do both to verify the input parameters and make the code changes score unchanged? @Property is the role. Below, we discuss the advanced features of Python @Property. To put it simply@Properyty is to change the invocation of a member function into a property assignment。 The following code is then available:
class Student (object):def __init__ (self,name,score):  self._name = name  Self._score = Score   @property def score (self): return Self._score@score. Setterdef score (self,score):If not isinstance (score,int):  Raise ValueError ("Invalid score!!!")  if score < 0 or score >:  Raise ValueError ("score must be between [0,100]!!!")  Self._score = score     @property def name (self): return self._nameS1 = Student ("Lily", +)#s1. Name = "Luly"S1.score =
A description of the above code:
  • As you may have found, my member variables have been changed to _name and _score, where the first is to increase readability, and the two variables are private. The second reason see the following misunderstanding analysis.
  • The S1.name = "Luly" line in the code above has a compile error Attributeerror:can ' t set attribute , which means it cannot be changed directly here, why? As you can see, in the code, I do not provide a set function named name, it is worth noting that s1._name = "Lucy" is allowed to run through. But as we said before, suppose the user is conscious enough not to manipulate variable names such as _xxx or __xxx .
  • According to the original intent of the code above, the name is a read-only property of the class. The score is modifiable.
  • The function of the @property modifier score is a simple get function that does not require any arguments (self does not need to pass in values), so we can call this function, that is, S1.score. (This is the use of the property, which translates the function call into the attribute access), which is equivalent to adding a layer of parcels to the score.
  • About @score.setter is the set function for the member variable that is wrapped with the score function. When we need to modify the value of _score, we use the score function, but like score is the member property of the class, such as the above: S1.score = 100, is actually equivalent to S1.score (100).
Note that the function name here is not necessarily score, can be any string, here just to say score function is _score package, such as the following code: We changed the score to AA, but in this way:
class Student (object):def __init__ (self,name,score):  self._name = name  Self._score = Score   @property def AA (self): return Self._score@AA. Setterdef AA (self,score):If not isinstance (score,int):  Raise ValueError ("Invalid score!!!")  if score < 0 or score >:  Raise ValueError ("score must be between [0,100]!!!")  Self._score = score     @property def name (self): return self._nameS1 = Student ("Lily", +)#s1. Name = "Luly"S1. AA = 100 # Here is the equivalent of S1. AA (+)
Well, the concept and usage of @property is over. In essence, a new function is defined, which performs the functions of set and get, and has a @property package. and assign these defined functions as attributes. Possible traps: The following code is a big trap, because now the function is no longer a simple function, but can be called directly with =, for example, the score function above the call unexpectedly is S1.score = 100. This will cause the following problem:
class Student (object):def __init__ (self,name,score):  self.name = name  Self.score = Score   @property def score (self): return Self.score@score. Setterdef score (self,score):If not isinstance (score,int):  Raise ValueError ("Invalid score!!!")  if score < 0 or score >:  Raise ValueError ("score must be between [0,100]!!!")  Self.score = score     @property def name (self): return self.name def func (self):  Self.score = score   S1 = Student ("Lily", +)S1.func ()
There are two big errors in the code above,
  • You will find that you cannot define any instances of student, why? First @property the score and name two member functions can be accessed as member variables, when the instance is defined, when the init function is called, Self.name = name, this sentence, Python treats the left side of Self.name as a function call, but we do not define a set function for the name variable, and the error message is: Attributeerror:can ' t set attribute.
  • Okay, let's comment on that.
    @property def name (self): return self.name
  • These two lines, then the next run is still wrong, why? Because the second line of the init function code, Self.score = Score, is fortunate that we have defined the score set function, then Self.score calls the score function when the last sentence of the score function is executed self.score = Score, we found that the left end of the formula or score function call, so reciprocating, and finally the function recursion depth to reach the upper limit exit program. This is actually a good code habit, that is, try not to let the name of the function and variable name, you can avoid these errors.

Resources


Python's @property

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.