Class Properties

Properties are very useful when you want to do something extra when a variable is set to a value or the value is "read" from the variable.  This requires using the special decorators:

@property<br>
@[variablename].setter

Example

Python
class PropertyClass():
    @property
        def x(self):
            print('getting x for you')
            return self._x

    @x.setter
        def x(self, value):
        print(f'setting x to {value} for you')
        self._x = value

    def __init__(self):
        self._x = 0

myClass = PropertyClass()
print(myClass.x)
myClass.x = 10
print(myClass.x)

Output

getting x for you
0
setting x to 10 for you
getting x for you
10

Notes

Contrast the above implementation with the following code, particularly in how the get and set functions are used:

Python
class MyOwnSetGetFunctions():
     def __init__(self):
          self.x = 0

     def get_x(self):
          print('getting x for you')
          return self.x

     def set_x(self, value):
          print(f'setting x to {value} for you')
          self.x = value

myClass = MyOwnSetGetFunctions()
print(myClass.get_x())
myClass.set_x(10)
print(myClass.get_x())

Output

getting x for you
0
setting x to 10 for you
getting x for you
10