Home >Backend Development >Python Tutorial >A brief introduction to the property function in Python
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)
Output result:
(5, 10) 100
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!