Detailed description of the Advanced Python property

Source: Internet
Author: User

Python has a small concept called a property function that can do something useful. In this article, we will see how to do the following:

    • To convert a class method to a read-only property
    • Re-implement a property setter and getter method

In this article, you will learn how to use built-in property functions in several different ways. If you want to read the end of the article, you can see how useful it is.

Begin

One of the simplest ways to use a property function is to use it as an adorner for a method. This allows you to turn a class method into a class property.

When I need to do some consolidation of values, I find this useful. Other people who want to get it used as a method find it useful when writing a conversion function.

Let's look at a simple example:

1 ########################################################################2 classPerson (object):3     """"""4  5     #----------------------------------------------------------------------6     def __init__(self, first_name, last_name):7         """Constructor"""8Self.first_name =first_name9Self.last_name =last_nameTen   One     #---------------------------------------------------------------------- A @property -     deffull_name (self): -         """ the Return The full name -         """ -         return "%s%s"% (Self.first_name, self.last_name)

In the above code, we created two class properties:self.first_name and self.last_name. Next

We created a full_name method that has a @property adorner.

This enables us to have the following interactions in the Python interpreter session:

1>>> person = person ("Mike","Driscoll")2>>>Person.full_name3 'Mike Driscoll'4>>>Person.first_name5 'Mike'6>>> Person.full_name ="Jackalope"7 Traceback (most recent):8File"<string>", Line 1,inch<fragment>9Attributeerror:can'T set attribute

This is a limitation, so let's take a look at another example where we can create a property that allows setting.

Replace setter and Getter methods with Python property

If you want to add a property that can be accessed using the normal dot symbol without destroying all the applications that depend on that code,

You can change it very simply by adding a property function:

1  fromDecimalImportDecimal2  3 ########################################################################4 classFees (object):5     """"""6  7     #----------------------------------------------------------------------8     def __init__(self):9         """Constructor"""TenSelf._fee =None One   A     #---------------------------------------------------------------------- -     defGet_fee (self): -         """ the Return the current fee -         """ -         returnSelf._fee -   +     #---------------------------------------------------------------------- -     defSet_fee (self, value): +         """ A Set the fee at         """ -         ifisinstance (value, str): -Self._fee =Decimal (value) -         elifisinstance (value, Decimal): -Self._fee =value -   inFee = Property (Get_fee, Set_fee)

We added a line at the end of this code. Now we can do this:

1>>> f =Fees ()2>>> F.set_fee ("1")3>>>F.fee4Decimal ('1')5>>> F.fee ="2"6>>>F.get_fee ()7Decimal ('2')

As you can see, when we use the property function In this way, it allows the fee property to set and get the value itself without breaking the original code.

Let's use the property decorator to rewrite this code to see if we can get a property value that is allowed to be set.

1  fromDecimalImportDecimal2  3 ########################################################################4 classFees (object):5     """"""6  7     #----------------------------------------------------------------------8     def __init__(self):9         """Constructor"""TenSelf._fee =None One   A     #---------------------------------------------------------------------- - @property -     deffee (self): the         """ - The fee property-the Getter -         """ -         returnSelf._fee +   -     #---------------------------------------------------------------------- + @fee. Setter A     deffee (self, value): at         """ - The setter of the fee property -         """ -         ifisinstance (value, str): -Self._fee =Decimal (value) -         elifisinstance (value, Decimal): inSelf._fee =value -   to #---------------------------------------------------------------------- + if __name__=="__main__": -f = Fees ()

The code above demonstrates how to create a setter method for the fee property. You can use a setter called @fee.

Decorative decoration The second method name is also a fee method to implement this. The setter is called when you do the following:

1 >>> f = Fees ()2"1"

If you look at the description of the attribute function , it has Fget, Fset, Fdel and doc several parameters. If you want to use the del command on a property,

You can use the @fee. Deleter Create another adorner to decorate the function with the same name to achieve the same effect of deletion.

Supplementary reading:
    • Getter and setter methods in Python
    • Description of the property in the official Python document
    • A discussion of adding a document string to a Python property function in StackOverflow

Detailed description of the Advanced Python property

Related Article

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.