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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With