Python Property has two usage methods: pythonproperty

Source: Internet
Author: User

Python Property has two usage methods: pythonproperty

Assume that a class is defined: C, which must inherit from the object class and has a private Variable _ x
Copy codeThe Code is as follows:
Class C:
Def _ init _ (self ):
Self. _ x = None
1. Now we will introduce the first method to use attributes:
Define three functions in this class for assignment, value, and deletion (the expression may not be clear here, please refer to the example)
Def getx (self ):
Return self. _ x
Def setx (self, value ):
Self. _ x = value
Def delx (self ):
Del self. _ x
X = property (getx, setx, delx ,'')

The prototype of the property function is property (fget = None, fset = None, fdel = None, doc = None), So define the corresponding function as needed.
Now the x attribute in this class has been defined. We can first define a C instance c = C () and then assign the value c. x = 100, value: y = c. x, delete: del c. x. Is it easy? See method 2
2. See the second method (added in 2.6)
First define a class C:
Copy codeThe Code is as follows:
Class C:
Def _ init _ (self ):
Self. _ x = None
The attributes are defined below.
@ Property
Def x (self ):
Return self. _ x
@ X. setter
Def x (self, value ):
Self. _ x = value
@ X. deleter
Def x (self ):
Del self. _ x

The names of the three functions in the same attribute must be the same ..

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.