Python built-in functions (51) -- property, pythonproperty

Source: Internet
Author: User

Python built-in functions (51) -- property, pythonproperty

English document:

Classproperty(Fget = None,Fset = None,Fdel = None,Doc = None)

Return a property attribute.

FgetIs a function for getting an attribute value.FsetIs a function for setting an attribute value.FdelIs a function for deleting an attribute value. AndDocCreates a docstring for the attribute.

If given,DocWill be the docstring of the property attribute. Otherwise, the property will copyFget'S docstring (if it exists). This makes it possible to create read-only properties easily usingproperty()As a decorator.

The@propertyDecorator turnsvoltage()Method into a "getter" for a read-only attribute with the same name, and it sets the docstringVoltageTo "Get the current voltage ."

A property object hasgetter,setter, AnddeleterMethods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.

 

Note:

1. property is a class used to encapsulate the attributes of a class. This property can be used to control whether the class is readable (set the fget parameter) and writable (set the fset parameter) based on actual needs) and can be deleted (set the fdel parameter ).

class C:    def __init__(self):        self._x = '_x in C'    def getx(self):        return self._x    def setx(self, value):        self._x = value    def delx(self):        del self._x    x = property(getx, setx, delx, "I'm the 'x' property.")
>>> C = C () >>> c. x # Call getx' _ x in c'> C. x = 'x had changed '# Call setx> c. x # Call getx 'x had changed '> del c. x # Call delx> c. x # call getxTraceback (most recent call last): File "<pyshell #34>", line 1, in <module> c. x File "<pyshell #28>", line 6, in getx return self. _ xAttributeError: 'C' object has no attribute '_ x'

2. The parameter doc indicates the description of the attribute. If not specified, it will be read from the method specified by the fget parameter.

>>> Help (c) Help on C in module _ main _ object: class C (builtins. object) | Methods defined here: | _ init _ (self) | Initialize self. see help (type (self) for accurate signature. | delx (self) | getx (self) | setx (self, value) | ---------------------------------------------------------------------- | Data descriptors defined here: | _ dict _ | dictionary for instance variables (if defined) | _ weakref _ | list of weak references to the object (if defined) | x | I'm the 'X' property. # the document string in the last line is I'm the 'X' property. >>> class C: def _ init _ (self): self. _ x = '_ x in c' def getx (self): "I'm the 'X' property. provide by getx "" return self. _ x def setx (self, value): self. _ x = value def delx (self): del self. _ x = property (getx, setx, delx) >>> help (C) Help on class C in module _ main __: class C (builtins. object) | Methods defined here: | _ init _ (self) | Initialize self. see help (type (self) for accurate signature. | delx (self) | getx (self) | I'm the 'X' property. provide by getx | setx (self, value) | items | Data descriptors defined here: | _ dict _ | dictionary for instance variables (if defined) | _ weakref _ | list of weak references to the object (if defined) | x | I'm the 'X' property. provide by getx # the document string in the last line is I'm the 'X' property. provide by getx

3. The more elegant way of property is to use it as a decoration device. The decorated method can be called as an attribute. At the same time, the. setter and. deleter decorators will be generated to specify the allowed methods and delete methods.

>>> class C:    def __init__(self):        self._x = '_x in C'    @property    def x(self):        """I'm the 'x' property."""        return self._x    @x.setter    def x(self, value):        self._x = value    @x.deleter    def x(self):        del self._x
>>> C = C () >>> c. x # Call getx' _ x in c'> C. x = 'x had changed '# Call setx> c. x # Call getx 'x had changed '> del c. x # Call delx> c. x # call getxTraceback (most recent call last): File "<pyshell #34>", line 1, in <module> c. x File "<pyshell #28>", line 6, in getx return self. _ xAttributeError: 'C' object has no attribute '_ x'

4. attributes are used instead of directly using fields, mainly because they can be controlled for malicious modification and deletion of class fields, and can be properly verified when setting attribute values.

>>> Class C: def _ init _ (self): self. _ name = ''@ property def name (self):" I'm the 'name' property. "" return self. _ name @ name. setter def name (self, value): if value is None: raise RuntimeError ('name can not be none') else: self. _ name = value >>> c = C () >>> c. name # access attribute ''> c. name = None # Traceback (most recent call last): File "<pyshell #84>", line 1, in <module> c. name = None File "<pyshell #81>", line 11, in name raise RuntimeError ('name can not be none') RuntimeError: name can not be None >>> c. name = 'Kim '# Set attributes >>> c. name # access attribute 'Kim '>>> del c. name # Delete attribute. Traceback (most recent call last): File "<pyshell #87>", line 1, in <module> del c. nameAttributeError: can't delete attribute >>> c. name 'Kim'

 

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.