Property in Python
In Python, a property is a special kind of attribute that allows for controlled access to an attribute's value. Properties are created using the @property decorator, which enables the definition of getter, setter, and deleter methods. This mechanism allows for the implementation of lazy attributes and other access control mechanisms, providing a way to manage how attributes are accessed and modified.
Overview
A property in Python allows you to combine the benefits of getter and setter methods with the straightforward access of instance variables through dot notation. This is achieved using the @property decorator, which enables you to define a method that acts as a getter. If you need to modify the property, you can add a setter using the @property_name.setter decorator. This approach allows you to start with simple instance variables and later transition to properties without changing client code.
Creating a Property
To create a property, you use the @property decorator with a method that has the property’s name. Here is an example:
class Temperature:
def __init__(self):
self._temp_fahr = 0
@property
def temp(self):
return (self._temp_fahr - 32) * 5 / 9
In this example, the temp method is decorated with @property, making it a read-only property. The method calculates the temperature in Celsius from the internal Fahrenheit value.
Adding a Setter
Without a setter, a property is read-only. To allow modification of the property, you need to add a setter. Here is how you can add a setter to the temp property:
class Temperature:
def __init__(self):
self._temp_fahr = 0
@property
def temp(self):
return (self._temp_fahr - 32) * 5 / 9
@temp.setter
def temp(self, new_temp):
self._temp_fahr = new_temp * 9 / 5 + 32
In this updated example, the @temp.setter decorator is used to define a setter for the temp property. This allows you to use standard dot notation to both get and set the property temp. Notice that the name of the method remains the same, but the decorator changes to the property name (temp, in this case), plus .setter indicates that a setter for the temp property is being defined.
Implementing Lazy Attributes
One of the powerful uses of properties in Python is the implementation of lazy attributes. Lazy attributes are those that are computed only when they are accessed for the first time, which can be particularly useful for expensive operations. By using the property decorator, you can intercept attribute access and execute the necessary operations only when needed.
Example: Lazy Attribute with @property
Below is an example of how to create a lazy attribute using the property decorator. This example demonstrates a User class where the profile_data attribute is loaded only when accessed for the first time.
class User:
def __init__(self, username):
self.username = username
self._profile_data = None
print(f"### User {username} created")
@property
def profile_data(self):
if self._profile_data is None:
print("_profile_data is None")
self._profile_data = self._get_profile_data()
else:
print("_profile_data is set")
return self._profile_data
def _get_profile_data(self):
# get the data from the server and load it into memory
print("*** Run the expensive operation")
fetched_data = "Extensive data, including thumbnail, \n followers, etc."
return fetched_data
In this example, the profile_data property checks if _profile_data is None. If it is, it calls the _get_profile_data method to perform an expensive operation and fetch the data. This ensures that the data is only fetched when necessary, achieving lazy evaluation.
Using Setters for Data Validation
Properties can also be used to enforce data validation when setting attribute values. By defining a setter method, you can control what values are allowed for a property.
Example: Property Setter for Data Validation
The following example shows how to use a property setter to ensure that a task's status is set to a valid value.
class Task:
# __init__ stays the same
@property
def status(self):
return self._status
@status.setter
def status(self, value):
allowed_values = ["created", "started", "completed", "suspended"]
if value in allowed_values:
self._status = value
print(f"task status set to {value}")
else:
print(f"invalid status: {value}") #1
#1 The best practice is to raise an exception (see section 12.4).
In this example, the status property has a setter method that checks if the provided value is one of the allowed statuses. If the value is valid, it sets the _status attribute; otherwise, it prints an error message. This approach ensures that only valid statuses can be assigned to the status property.
For more detailed information, you can refer to The Quick Python Book, Fourth Edition and Python How-To.
| Book Title | Usage of property | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-------------------|-----------------|-------------------------------|---------------|-----------------------|
| [The Quick Python Book, Fourth Edition](https://www.manning.com/books/the-quick-python-book-fourth-edition) | Discusses the use of `@property` and `@property_name.setter` decorators to create and modify properties, allowing for straightforward access and modification of instance variables. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/163) | Provides a detailed explanation of how to create properties and add setters, with code examples demonstrating the transition from simple instance variables to properties. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/167) | Connects properties to getter and setter methods, emphasizing the ease of transitioning from instance variables to properties without changing client code. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/163) | Uses a `Temperature` class example to illustrate the creation of a read-only property and the addition of a setter. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/167) | Highlights practical use cases such as converting temperature units and modifying properties using standard dot notation. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/167) |
| [Python How-To](https://www.manning.com/books/python-how-to) | Explores properties as a means to control attribute access, including lazy attributes and data validation through setters. [more](https://livebook.manning.com/book/python-how-to/chapter-9/225) | Delves into the implementation of lazy attributes and data validation, providing examples of how properties can manage attribute access and modification. [more](https://livebook.manning.com/book/python-how-to/chapter-9/226) | Discusses lazy evaluation and data validation, showing how properties can be used to implement these concepts effectively. [more](https://livebook.manning.com/book/python-how-to/chapter-9/225) | Provides examples such as a `User` class with a lazy-loaded `profile_data` attribute and a `Task` class with a status property that validates input. [more](https://livebook.manning.com/book/python-how-to/chapter-9/228) | Demonstrates practical applications like lazy loading of user data and enforcing valid task statuses through property setters. [more](https://livebook.manning.com/book/python-how-to/chapter-9/225) |
FAQ (Frequently asked questions)
What is a property in Python?
How do you create a read-only attribute in Python?
What is the purpose of the property decorator in Python?
How can you implement lazy attributes in Python?
How does the property decorator help in creating lazy attributes?
What happens when the profile_data property is accessed for the first time?
What is lazy evaluation in the context of Python properties?
How do properties enable lazy evaluation in Python?
What is a property in Python?
How do you create a property in Python?
How can you modify a property in Python?
What is the advantage of using properties in Python?
How do you define a getter for a property in Python?
How do you define a setter for a property in Python?
What does the .setter decorator indicate in Python?
Can you use dot notation to access properties in Python?