Property decorators in Python are used to define getter, setter, and deleter methods for class attributes in a more readable and Pythonic way. Instead of manually defining methods like get_name() and set_name(), you can use the @property decorator to create getter methods and the @<property_name>.setter and @<property_name>.deleter decorators for setters and deleters, respectively.
Here are 10 Python snippets demonstrating how to use property decorators for managing class attributes.
1. Basic Property with Getter
classPerson:def__init__(self,name):self._name = name@propertydefname(self):returnself._name# Usagep =Person("Alice")print(p.name)# This calls the getter method
Explanation: The @property decorator is used to define the getter method for the name attribute.
2. Property with Setter
classPerson:def__init__(self,name):self._name = name@propertydefname(self):returnself._name@name.setterdefname(self,value):ifnot value:raiseValueError("Name cannot be empty")self._name = value# Usagep =Person("Alice")p.name ="Bob"# This calls the setter methodprint(p.name)
Explanation: The setter method is defined using @name.setter. It allows you to set a value for the name attribute, with validation.
3. Property with Deleter
Explanation: The @name.deleter decorator is used to define the method for deleting the name attribute. In this case, we print a message before deleting it.
4. Property with a Computed Value
Explanation: The area property calculates a value dynamically rather than storing it. It’s automatically updated based on the width and height.
5. Property with Cached Getter
Explanation: This example shows a computed property where the Fibonacci number is cached to optimize performance.
6. Setter with Validation
Explanation: The setter ensures that the age attribute cannot be set to a negative value.
7. Read-Only Property
Explanation: circumference is a read-only property derived from the radius.
8. Property with Logging
Explanation: The setter for celsius logs the change each time the temperature is set.
9. Private Attribute with Property Access
Explanation: A private attribute (_balance) is accessed and modified using the property decorators.
10. Class Property
Explanation: A class-level property is created using the @classmethod and @property decorators together. It tracks the total number of cars created.
Key Concepts:
Getter (@property): Defines a method to access the value of an attribute.
Setter (@property_name.setter): Defines a method to set the value of an attribute with validation or other logic.
Deleter (@property_name.deleter): Defines a method to delete an attribute.
Read-only Properties: Properties that can only be accessed but not modified.
Validation: Properties can include validation logic to ensure data integrity.
Caching/Optimization: You can cache values to improve performance, especially in computed properties.
Private Attributes: Properties provide controlled access to private attributes, which cannot be directly accessed outside the class.
Using property decorators helps to keep the class interface clean and intuitive, while still encapsulating the internal logic.
class Fibonacci:
def __init__(self, n):
self._n = n
self._fib_cache = {}
@property
def fibonacci(self):
if self._n in self._fib_cache:
return self._fib_cache[self._n]
if self._n <= 1:
return self._n
result = self._n * self.fibonacci # Recursive logic for Fibonacci
self._fib_cache[self._n] = result
return result
# Usage
fib = Fibonacci(10)
print(fib.fibonacci)
class Person:
def __init__(self, age):
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
# Usage
p = Person(25)
p.age = -5 # This will raise a ValueError