Investigate Student class:
class Student (object): def __init__ (self, Name, score): = name = Score
When we want to modify the Scroe property of a Student, we can write this:
s = Student ('Bob',60
But it can also be written like this:
S.score = 1000
Obviously, assigning a value directly to a property does not check the validity of the score.
If you are using two methods:
classStudent (object):def __init__(self, Name, score): Self.name=name self.__score=scoredefGet_score (self):returnSelf.__score defSet_score (self, score):ifScore < 0orScore > 100: RaiseValueError ('Invalid score') self.__score= Score
In this way, S.set_score (1000) will be an error.
This use of the Get/set method to encapsulate access to a property is common in many object-oriented programming languages.
But writing S.get_score () and S.set_score () did not directly write S.score directly.
Is there a way to both worlds? ----have.
Because Python supports higher-order functions, you can use adorner functions to "decorate" the Get/set method into a property invocation:
classStudent (object):def __init__(self, Name, score): Self.name=name self.__score=score @propertydefscore (self):returnSelf.__score@score. Setterdefscore (self, score):ifScore < 0orScore > 100: RaiseValueError ('Invalid score') self.__score= Score
Note: The first score (self) is the Get method, decorated with @property, the second score (self, score) is the set method, decorated with @score.setter, @score. Setter is the previous @ The property is decorated by-product.
Now you can set the score as you would with properties:
>>> s = Student ('Bob', S.score)print 60>> > s.score =Traceback (most recent): ... Valueerror:invalid score
Indicates that the set method is actually called for score assignment.
@property in Python and