Properties

Updated on 28 Dec 2022

The @property decorator is a built-in function that allows us to define methods that can be accessed like an attribute. Typcially we might do this because we want to add additional behaviour to the getting or setting of an attribute, i.e. decoration or validation.

In my case I sometimes find it easier to read the Python code when I have explicitly stated that this is a publicly accessible property.

getter

In this example, we simply add @property to the start of the method; which we have also signified returns an int.

@property
def num_quotes(self) -> int:
    return len(self.quotes)

Accessing this property is the same as a normal attribute

import Quote

# 1st Quote is the filename
# 2nd Quote is the classname
#
# num_quotes is a property of the Quote class

myQuotes = Quote.Quote() 
print(myQuotes.num_quotes)

This can be useful when we want to add some additional behavior to the getting or setting of an attribute, or when we want to define a method that is more readable and easier to use than a traditional method.

Note that because we haven’t defined a setter for this property, trying to write to it will cause an error.

setter

To create a property setter, we use the @<property_name>.setter syntax. The example that I have makes no sense, it is purely here to demonstrate the syntax used.

@num_quotes.setter
def num_quotes(self, value):
    self.quotes.append("This crazy number was set {0}".format(value))

Accessing this property is the same as a normal attribute

import Quote

# 1st Quote is the filename
# 2nd Quote is the classname
#
# get_all_quotes is a property of the Quote class

myQuotes = Quote.Quote() 
myQuotes.num_quotes = 10

print(myQuotes.get_all_quotes())

)