Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Implementing Java-style getters and setters in Python

"""
When a member needs to be slightly protected and cannot be simply 
exposed as a public member, use Python’s property decorator to 
accomplish the functionality of getters and setters.
"""
class Square(object):
    def __init__(self, length):
        self._length = length

    @property
    def length(self):
        return self._length

    @length.setter
    def length(self, value):
        self._length = value

    @length.deleter
    def length(self):
        del self._length

r = Square(5)
r.length  # automatically calls getter
r.length = 6  # automatically calls setter
Source by docs.quantifiedcode.com #
 
PREVIOUS NEXT
Tagged: #Implementing #getters #setters #Python
ADD COMMENT
Topic
Name
8+3 =