Ticker

6/recent/ticker-posts

@property Decorator in Python

@property Decorator in Python

Introduction:
The @property decorator in Python is a powerful tool used to create read-only properties for class attributes. It allows us to define getter methods for these attributes, enabling access to their values without directly exposing the underlying attribute.

Usage:
To use the @property decorator, you need to define a method with the same name as the attribute you want to access, and annotate it with @property. The method will be used as a getter for that attribute.

Syntax:

python
class MyClass:
def __init__(self):
self._my_attribute = None

@property
def my_attribute(self):
return self._my_attribute

Explanation:
In the above example, we have a class MyClass with a private attribute _my_attribute. We want to access this attribute through a read-only property, so we define a method my_attribute and decorate it with @property. Now, whenever we try to access my_attribute, it will call the my_attribute method and return the value of _my_attribute.

Example:

python
class Circle:
def __init__(self, radius):
self._radius = radius

@property
def radius(self):
return self._radius

@property
def area(self):
return 3.14 * self._radius * self._radius

# Usage
circle = Circle(5)
print("Radius:", circle.radius) # Output: 5
print("Area:", circle.area) # Output: 78.5

In the example above, we have a class Circle with a private attribute _radius. By using @property, we can access the radius attribute using the circle.radius syntax. Similarly, we have another property area that calculates and returns the area of the circle based on its radius.

Conclusion:
The @property decorator in Python provides an elegant way to control access to class attributes by defining custom getter methods. It enhances code readability and maintainability by encapsulating attribute access logic.

Post a Comment

0 Comments