Introduction to the basic usage of the property decorator in Python

Source: Internet
Author: User
Python's @property decorator is used to turn a class's method into a class's property call, and then @property itself creates another adorner that assigns a value to the property in a single way. The following is a read-write property for the class that is set after the @property is used in the class, and the ReadOnly and write-only properties.

The all method sets the read-write property, can set this property, or can read the property, as shown in the 28 line, if the __init__ () method is not defined, it can only be used if the property is set first. In 32 rows, if you want to know the value of the Write property, you will get an error. And in 34 rows, there is no way to continue to give ReadOnly this system attribute assignment. After using the @property, Python "Private variables" can be implemented, not really private, the real private is more complex, but can also be implemented through @property? After studying again to write.

Class Useproperty (object):    def __init__ (self):        Self._all = 233    @property    def all:        return Self._all    @all. Setter    def all (self, v):        self._all = v    @property    def readonly (self):        return Self._all    @property    def write (self):        raise Attributeerror (' This is not a readonly attribute. ')    @write. Setter    def write (self, value):        self._write = VALUEP = Useproperty () print P.allp.all = 100print P.allp.write = 233# Print p.writeprint p.readonly# p.readonly = 10

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.