Search code examples
pythonpython-2.7propertiespython-2.xgetter-setter

How to Use Getter Without Setter


I am using python 2.7.

I have the following class:

class Test:

    def __init__(self):
        self._pos_a = ['test_1']
        self._pos_b = ['test_2']


    @property
    def pos_a(self):
        return self._pos_a

    @property
    def pos_b(self):
        return self._pos_b


    if __name__ == "__main__":
        x = Test()
        x.pos_a = True
        print x.pos_a

>>> True

My understanding is that by using the property decorator, I am essentially establishing a getter method for each of my two class atributes. Since I am not creating a setter method though, I would expect that my assignment of "True" to x.pos_a would raise an error. The error should be that I can't set the value of an attribute for which there is a getter method but no setter method. Instead, the value is set to "True" and it prints with no problem. How do I implement this so as to achieve that result? I want users to be able to "get" these values, but they should not be able to set them.


Solution

  • You'll need to inherit from object for properties to work properly.

    class Test(object):
        ...
    

    That's because properties are implemented with descriptors and only new-style classes support descriptors.