Python built-in function proprety ()

Source: Internet
Author: User

Tag: Property Python property () Python built-in function

The property can access a Python-defined function as an attribute, 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:

Class cls (object):     def __init__ (self):         self.__x = none         def getx (self) :        return self.__x          def setx (self, value):         self.__x  = value             def delx ( Self):        del self.__x              x = property (getx, setx, delx,  ' set x  property ')  if __name__ ==  ' __main__ ':     c = cls ()     c.x = 100    y = c.x     Print ("SET & GET&Nbsp;y: %d " % y)          del c.x     print ("del c.x & y: %d"  % y)
Run Result: Set & get Y:100del c.x & Y:100 defines three functions in this class, respectively, as assignment, value, delete variable property function prototype as property (fget=none,fset=none,fdel= None,doc=none), the above example assigns a value according to its own definition of the corresponding function.

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

Class cls (object):     def __init__ (self):         self.__x = None               @property     def x (self):         return  self.__x         @x.setter    def  X (Self, value):        self.__x = value              @x.deleter    def x (self):        del self.__x if __name__ ==  ' _ _main__ ':     c = cls ()     c.x = 100     y = c.x    print ("set & get y: %d"  %  y)   &nbsP;      del c.x    print ("del c.x &  y: %d " % y)
Run Result: Set & get Y:100del c.x & y:100 Description: The same property __x three function names.


This article is from the "Lu Yaliang" blog, make sure to keep this source http://luyaliang.blog.51cto.com/3448477/1767089

Python built-in function proprety ()

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.