Property annotations in Python

Source: Internet
Author: User

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

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.