6 comments on “Read-Only Properties in Python

  1. Hello, from example show in article “Set Once Property” does not come into effect:

    a = SOPTest(‘value1’)
    print a.prop
    value1
    a.prop = “value2”

    “prop” property still can be changed. Could you correct me if I take a misunderstand ?

    Like

  2. For SetOnceProperty since val is a positional argument it will always need to be set when we create an instance. How will this work if we want to set it to something different? Could you give a usage example where we initialize and then set the value just once.?

    Thanks

    Like

    • Assuming I understand your question properly, you can set it up to optionally set it later like this:

      class SOPTest():
      prop = SetOnceProperty()

      def __init__(self, val=None):
          if val is not None:
              self.prop = val
      

      Or you can force doing it later like this:

      class SOPTest():
      prop = SetOnceProperty()

      Like

  3. Thanks! This was what I needed. But I had to make the SetOnceProperty inherit for object (“new style class”) in order to make it work, /Jonas

    Like

Leave a comment