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.
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,
Resources
Python's @property