Attribute vs. Property in Python
Normally, when I talk about classes as it relates to programming I use the word property
to describe a piece of state stored on a class, which represents a characteristic or feature. For example, in the following python Celsius class, I would call temperature
a property of that class.
class Celsius:
def __init__(self, temperature=0):
self.temperature = temperature
But Today I Learned that in python temperature
is specifically called an attribute
. Thats because python reserves the word property
for a special form of attribute that allows a getter and setter method to be defined for an attribute. This gives a developer more control over how an attribute is accessed, modified or deleted. The following python class provides an example of a property.
class Celsius:
def __init__(self, temperature=0):
self._temperature = temperature
@property
def temperature(self): # the @property decorator defines the getter of the temperature property
return self._temperature
@temperature.setter
def temperature(self, value): # the @temperature.setter decorator registers this method as the setter for the temperature property
if value < -273.15:
raise ValueError("Temperature below -273.15 is not possible.")
self._temperature = value
def to_fahrenheit(self): # a run of the mill class method that uses the temperature property exactly like you would use a regular old attribute
return (self.temperature * 1.8) + 32
This example defines a class Celsius that has a property temperature. The property is created using the @property decorator and has a getter and a setter method. The getter method returns the value of the private attribute _temperature, and the setter method validates the input value and assigns it to _temperature. The property can be accessed and modified as a normal attribute, but with the added benefits of the property methods.
The take away here is that a property and an attribute are different, but not really, but technically they are, but they look the exact same to the user of a class. Confused? Don’t be.