coderz.py

Keep Coding Keep Cheering!

@property Decorator in Python

JOIN Clause

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 @property Decorator:

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:

  • Use it to define getter methods for class attributes, especially when the attribute is a calculated value or has some logic behind it.
  • Use the @property_name.setter decorator to define setter methods for class attributes, which allows you to add validation and logic to the attribute setter.
  • Use private attributes (e.g. _radius) to store the actual value, and use properties to expose it to the outside world.
  • Be careful not to add too much complexity to the getter and setter methods, as it can make the code harder to understand and maintain.
  • When using the @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.
  • Use @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.

Defining setter and deleter methods with @property Decorator:

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.

Python property() function:

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: 

  • fget() – used to get the value of attribute
  • fset() – used to set the value of attribute
  • fdel() – used to delete the attribute value
  • doc() – string that contains the documentation (docstring) for the attribute

Return: Returns a property attribute from the given getter, setter and deleter.

Note:

  • If no arguments are provided, the property() method returns a base property attribute with no getter, setter, or deleter.
  • If doc is not provided, the property() method uses the getter function’s docstring.
Example:

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

Follow Me

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement