@property in Python and

Source: Internet
Author: User

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

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.