Home > Backend Development > Python Tutorial > A brief introduction to the property function in Python

A brief introduction to the property function in Python

不言
Release: 2018-10-11 15:49:55
forward
2888 people have browsed it

This article brings you a brief introduction to the property function in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Using the Property function in Python, you can call functions in a class as attributes.

Case

__metaclass__=type
class Rectangle:
    def __init__(self):
        self.width=0
        self.height=0
    def setSize(self,size):
        self.width,self.height=size
    def getSize(self):
        return self.height,self.width
    size=property(getSize,setSize)
r=Rectangle()
r.width=10
r.height=5
ret=r.size
print(ret)
r.size=100,50
rets=r.width
print(rets)
Copy after login

Output result:

(5, 10)
100
Copy after login

Property function An attribute size is created, and the accessor function is used as a parameter (value is obtained first, then assigned). Although they look like properties, the properties of size still depend on the calculations of getSize and setSize.

In fact, Property is not a real function but a class with a lot of special methods, and it is these methods that can complete all the work. Involved methods:

#The above three methods define the rules of descriptors. The object that implements any one of these methods is called a descriptor. What's special about descriptors is how they are accessed. For example, when a program reads a property, if the property is bound to an object that implements the __get__ method, the __get__ method will be called instead of simply returning the object. This is the property mechanism of the object, also called the binding method.

The above is the detailed content of A brief introduction to the property function in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template