Python built-in Method - property()

www.igif‮it‬dea.com

The property() function is a built-in Python method that is used to define properties of an object. A property is an attribute that is accessed like a normal attribute, but it is actually the result of a method call.

The syntax for the property() function is as follows:

property(fget=None, fset=None, fdel=None, doc=None)
  • fget (optional): A function to get the value of the property.
  • fset (optional): A function to set the value of the property.
  • fdel (optional): A function to delete the value of the property.
  • doc (optional): A string that describes the property.

Here is an example of how the property() function can be used to define a property:

class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        self._width = value

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        self._height = value

    @property
    def area(self):
        return self._width * self._height

In this example, we define a Rectangle class that has width, height, and area properties. The width and height properties are defined using the @property decorator and setter method, which allows us to define methods that will be called when the property is accessed or modified. The area property is defined using only the @property decorator, as it is read-only and does not need a setter method.

By defining properties in this way, we can encapsulate the internal state of the Rectangle object and control how it is accessed and modified. This can be useful for enforcing data validation, calculating derived values, and providing a more user-friendly interface for accessing the object's attributes.

The property() function is a powerful built-in method in Python that can be used to define complex properties and customize their behavior. It is often used in object-oriented programming and software design patterns.