Can the adorner (decorator) dynamically add functionality to the function? For class methods, adorners work as well. Python built-in
@property Decorator is responsible for turning a method into a property invocation:
Class Student (object): @propertydef score (self): return self._score@score.setterdef score (self, value): If not Isinstance (value, int): Raise ValueError (' score must is an integer! ') If value < 0 or value > 100:raise valueerror (' score must between 0 ~ 100! ') Self._score = value
The implementation of @property is more complex, we first examine how to use. To turn a getter method into a property, just add @property to
, the @property itself creates another adorner @score. Setter, responsible for changing a setter method into a property assignment, so I
They have a controllable property operation:
>>> s = Student () >>> S.score = OK, actual conversion to S.set_score >>> S.score # OK, actual conversion to S.get_score () 60>>> S.score = 9999Traceback (most recent call last): ... Valueerror:score must between 0 ~ 100!
@property, when we operate on an instance property, we know that the property is probably not directly exposed, but rather by Gett
Er and setter methods to implement.
You can also define read-only properties, define getter methods only, and do not define setter methods as a read-only property:
Class Student (object): @property def Birth (self): return Self._birth @birth. Setter #设置了set和get方法 def birth (self, value): Self._birth = value @property #设置了get方法 def-age (self): return 201 4-self._birthc=student () C.birth=10;print c.age
D:\chinaUnicom\Chinese\python.exe D:/python/test1/test3.py2004process finished with exit code 0
This article is from the "matengbing" blog, make sure to keep this source http://matengbing.blog.51cto.com/11395502/1905757
Property annotations in Python