Python Property Function

Last modified: 
Friday, May 1st, 2015
Topics: 
Python

The property function makes it easy to create highly abstracted and efficient getter/setter functionality. These can be accessed and updated like regular properties.

Examples

__metaclass__ = type

class Box:
    def __init__(self):
    self.width  = 0
    self.height = 0
    self.depth  = 0

    def setSize(self, size):
    self.width, self.height, self.depth = size

    def getSize(self):
        return self.width, self.height, self.depth

    size = property(getSize, setSize)



b = Box()
b.width  = 30
b.height = 30
b.depth  = 60
print b.size # (30, 30, 60)

b.size = 22, 33, 44
print b.size # (22, 33, 44)

b.height = 66
print b.size # (22, 66, 44)
print b.depth # 44

Note

This is only guaranteed to work on so-called new-style classes. Old-style classes may find your getter working but not your setter.

References


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.