In python code I often see the use of @property.
If I understand correctly, with the property function a getter setter and deleter can be defined.
Why would one use @property if the setter and deleter are not defined (@x.setter, @x.deleter)? Isn't this the same as not using @property at all?
The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.
What the @property decorator does, is declare that it can be accessed like it's a regular property. This means you can call full_name as if it were a member variable instead of a function, so like this: name = person.full_name. instead of. name = person.full_name()
The @property Decorator In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None)
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
It creates an API that does not allow a value to be set. This is similar in other languages to a constant.
Defining a property with a getter function but without a setter can be very useful in certain scenarios. Lets say you have a model as below in django; a model is essentially a database table with entries called fields. The property hostname is computed from one or more fields in the model from the database. This circumvents needing another entry in the database table that has to be changed everytime the relevant fields are changed.
The true benefit of using a property is calling object.hostname()
vs. object.hostname
. The latter is passed along with the object automatically so when we go to a place like a jinja template we can call object.hostname
but calling object.hostname()
will raise an error.
The example below is a virtualmachine model with a name field and an example of the jinja code where we passed a virtualmachine object.
# PYTHON CODE
class VirtualMachine(models.Model):
name = models.CharField(max_length=128, unique=True)
@property
def hostname(self):
return "{}-{}.{}".format(
gethostname().split('.')[0],
self.name,
settings.EFFICIENT_DOMAIN
)
# JINJA CODE
...start HTML...
Name: {{ object.name }}
# fails
Hostname: {{ object.hostname() }}
# passes
Hostname: {{ object.hostname }}
...end HTML...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With