2 Ways to use Python property properties

Source: Internet
Author: User
Suppose a class is defined: C, the class must inherit from the object class and have a private variable _x
Copy the Code code as follows:


Class C:
def __init__ (self):
Self.__x=none
   1. The first method of using attributes is now introduced:
Define three functions in the class to use as assignment, value, and delete variables (the expression may not be clear here, see 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 property function prototype is property (Fget=none,fset=none,fdel=none,doc=none), so the corresponding function can be defined according to its own needs.
Now that the X attribute in this class has been defined, we can first define an instance of C c=c (), then assign the value c.x=100, y=c.x, delete: Del c.x. Isn't it simple? Take a look at the second method
   2. See the second method (new in 2.6)
First define a Class C:
Copy the Code code as follows:


Class C:
def __init__ (self):
Self.__x=none
The properties are now defined as follows
@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 three function names of 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.