@property investigate Student class:classStudent (object):def __init__(self, Name, score): Self.name=name Self.score=score when we want to modify the Scroe property of a Student, we can write this: s= Student ('Bob', 59) S.score= 60But it can also be written like this: S.score= 1000obviously, 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 This way, S.set_score (1000) will have an error. This use of Get/The 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? ----there is. Because Python supports higher-order functions, in functional programming we introduce the adorner function, which can be used with the adorner function to get/the Set method "Decorates" into a property call: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', 59)>>> S.score = 60>>>PrintS.score60>>> S.score = 1000Traceback (most recent): ... Valueerror:invalid score shows that the set method is actually called for the score assignment. Task if you do not define a set method, you cannot assign a value to the property, and you can create a read-only property. Please add a grade attribute to the student class, and calculate a with score (>=80), B, C (<60).
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??? S= Student ('Bob', 59)PrintS.grades.score= 60PrintS.grades.score= 99PrintS.grade
The decorator is really not what I can understand, and then look slowly. From the magical interpretive language of Python.
Python decorator [email protected]