The @property
decorator in Python is used to define a method as a “getter” for the boundaries of a class attribute. It allows you to define a method that is accessed like an attribute, without needing to invoke it like a method.
Here’s an example:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
c = Circle(5)
print(c.radius) # prints 5
c.radius = 10
print(c.radius) # prints 10
In this example, the @property
decorator is used to define the radius
method as a getter for the _radius
attribute. The @radius.setter
decorator is used to define a setter method for the radius
property, which allows you to change the value of the _radius
attribute.
This way, you can use the Circle.radius as a variable without invoking it like a method, it would make it look like an attribute rather than a method.
Also, It is worth noting that, property decorator can also be used to define a method as a “setter” for a class attribute using @property_name.setter
Using the @property
decorator can make your code more readable and maintainable by allowing you to access class attributes like properties, rather than having to invoke methods. It also allows you to add logic and validation to the getter and setter methods, which can help ensure that the attribute is always in a valid state.
Here are some best practices for using the @property
decorator:
@property_name.setter
decorator to define setter methods for class attributes, which allows you to add validation and logic to the attribute setter._radius
) to store the actual value, and use properties to expose it to the outside world.@property
decorator, it is a good idea to add a docstring to the property method explaining what it does and how it should be used.@property
and @property_name.setter
decorators together to define a read-only property by omitting the setter method.Overall, the @property
decorator is a powerful tool that can help you write more maintainable and readable code, but it should be used with care and with consideration for its impact on the overall design of your codebase.
Similarly to the getter method (which we defined in the previous example), we can define setter and deleter methods for any attribute in Python that uses @property.
The setter method will set the attribute’s value, and the deleter method will remove the attribute from memory.
Let’s add a setter and deleter method to our fullname attribute. We use a special syntax to define a setter and deleter method for an attribute with @property decorator set on its getter method, where we put @ATTRIBUTE NAME.setter and @ATTRIBUTE NAME.deleter decorators on function with the same name as the ATTRIBUTE NAME.
The Python property() function returns the object of the property class and is used to create class properties.
Syntax: property(fget, fset, fdel, doc)
Parameters:
Return: Returns a property attribute from the given getter, setter and deleter.
Note:
Here’s an example of using the property()
method to define a class attribute called age
that can be read and written, but only allows positive integer values:
class Person:
def __init__(self):
self._age = None
def get_age(self):
return self._age
def set_age(self, value):
if isinstance(value, int) and value > 0:
self._age = value
else:
raise ValueError("Age must be a positive integer")
age = property(get_age, set_age)
person = Person()
person.age = 30
print(person.age) # prints 30
person.age = -5 # raises ValueError: Age must be a positive integer
In this example, the get_age()
method is defined as the getter for the age
attribute, and the set_age()
method is defined as the setter. The age = property(get_age, set_age)
line creates the age
attribute and sets the getter and setter methods. The set_age()
method checks the value passed to it, if it is a positive integer it assigns the value to _age else raises an exception.
Note: also read about Python Decorators
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…