How to use Python accessor @property

Source: Internet
Author: User

@property can access a python-defined function as a property, providing a more friendly way to access it, but sometimes setter/getter is Needed.

Suppose a class CLS is defined, which must inherit from the object class, with a private variable __x

1. The first method of using Attributes:

#!/usr/bin/env python#-*-coding:utf-8-*-#blog.ithomer.net classCls (object):def __init__(self): self.__x=NonedefGetx (self):returnSelf.__x         defsetx (self, value): self.__x=valuedefDelx (self):delSelf.__xx= Property (getx, setx, delx,'set X property') if __name__=='__main__': C=Cls () c.x= 100y=c.xPrint("Set & get y:%d"%Y)delc.xPrint("del c.x & y:%d"% Y)

Operation Result:

Set & Get Y:100
Del c.x & y:100

Define three functions in the class, used as assignment, value, Delete variable

Property function prototype is property (fget=none,fset=none,fdel=none,doc=none), The above example according to their own definition of the corresponding function to assign a Value.


2. Second method (new in 2.6)
With method one, first define a class cls, which must inherit from the object class, with a private variable __x

?
classCls (object):def __init__(self): self.__x=None @propertydefx (self):returnSelf.__x@x.setterdefx (self, value): self.__x=value @x.deleterdefx (self):delSelf.__x if __name__=='__main__': C=Cls () c.x= 100y=c.xPrint("Set & get y:%d"%Y)delc.xPrint("del c.x & y:%d"% Y)


Operation Result:
Set & Get Y:100
Del c.x & y:100
Description: the three function names of the same property __x are the Same.

How to use Python accessor @property

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.