Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 867
Malonge Avatar asked Jan 26 '17 00:01

Malonge


People also ask

Can I have a getter without a setter?

If your class is going to be used in the environment where setter is not required (e.g. ORM / dependency injection / serialization frameworks), it should be OK to do not use setter. In this particular case setter does not make much sense since variable is final and set only once.

What can I use instead of getters and setters?

You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code. I found it pretty fine and easy to use.

How do you avoid setters?

The simplest way to avoid setters is to hand the values to the constructor method when you new up the object. This is also the usual pattern when you want to make an object immutable.

What is a getter only property?

The JavaScript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified.


1 Answers

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.

like image 132
wim Avatar answered Nov 11 '22 10:11

wim