Class Properties
Date: February 14th 2016
Last updated: February 15th 2016
I highly recommend reading this article about properties: Properties vs. Getters and Setters.
In my example I have put constraints on length (not width). Both width and length are public so they can be changed by altering self.width or self.length. The only difference is the property decoration which restricts values of length to fall between 0 and 50.
#!/usr/bin/python3
# classproperties.py
class rectangle(object):
"""
Define attributes of a rectangle.
Requires 2 arguments; width and length.
"""
def __init__(self, width, length):
self.width = float(width)
self.length = float(length)
def calculate_area(self):
"""
Calculate area of a rectangle. Takes 2 arguments.
Examples
>>> rectangle(2,2).calculate_area()
4.0
>>> rectangle(0,8).calculate_area()
0.0
"""
return self.width * self.length
# getter function using property method
area = property(fget=calculate_area,
doc="calculates area of a rectangle")
@property
def length(self):
return self.__length
# The following decoration follows the name above
# if @property decorated 'l' instead of 'length',
# the decoration here would be @l.setter
#
# Note that def length now has two arguments, which is
# different from above. This is possible because of the
# decorator.
@length.setter
def length(self, length):
if length < 0:
self.__length = 0.0
elif length > 50:
self.__length = 50.0
else:
self.__length = length
# the following is used only to execute as a program
# I added width and length as arguements at command line...
# e.g. python classproperty.py 5 10
if __name__ == "__main__":
import sys, doctest
doctest.testmod(sys.modules[__name__])
r = rectangle(sys.argv[1], sys.argv[2])
print(r.area)
r.length = 100
print(r.area)
Execute at command line
python classproperty.py 6 70
#prints 300.00
#prints 300.00
#On instantiation length is set to 50
# the property method (r.area) prints out 6 * 50 (300.00)
#In the second printed statement I tried to make length 100
# this got set to 50 and subsequently prints the same amount
python classproperty.py 6 25
#prints 150.00
#prints 300.00
#Note the second print statement still includes the attempt
# to set length to 100 which got changed to a max of 50 (6 * 50)
# and returned 300.00