Properties

For properties using the decorator mechanism it is essential that you use the same name for the getter and the setter. The advantage of properties are two aspects:

  • the client code using the properties have a simple interface (the real setter and getter are hidden)
  • read and write access allow additonal operation like verification and/or conversion

In [23]:
from contracts import contract

class Foo(object):
    @contract(init_value='int,>=0')
    def __init__(self, init_value):
        self.__value = init_value

    @property
    @contract(returns='int,>=0')
    def value(self):
        return self.__value

    @value.setter
    @contract(new_value='int,>=0')
    def value(self, new_value):
        self.__value = new_value

foo = Foo(1234)
print("foo.value is %s" % foo.value)
foo.value = 4321
print("foo.value is %s" % foo.value)


foo.value is 1234
foo.value is 4321

In [ ]: