0

I trying to workout a way to make attributes immutable in my class. This is what I have come-up with, It appears to work. But is it acceptable?

It feels like a hack or there maybe a different way to achieve this. Is this acceptable? How else can could this be achieved?

class RankCalculator():


       def __init__(self, votesup=None, votesdown=None):
           self.__dict__['votesup'] = max(votesup, 0)
           self.__dict__['votesdown'] = max(votesdown, 0)


       def __setattr__(self, name, value):
            """
            Object state cannot be modified after it is created
            """
            raise TypeError('objects are immutable')

       @property
       def score(self):
          return float(self._score())

self._score() omitted for brevity.

MarkK
  • 968
  • 2
  • 14
  • 30
  • Why not just use read-only properties, like you're *already doing with `score`*? – jonrsharpe Aug 25 '15 at 14:32
  • @jonrsharpe I want to set them at object creation once, would read-only properties allow this? – MarkK Aug 25 '15 at 14:34
  • Yes, just assign to the *"private-by-convention"* attribute backing them, e.g. `_score`. – jonrsharpe Aug 25 '15 at 14:34
  • @jonrsharpe could you post an example? I'm not 100% sure what you mean. – MarkK Aug 25 '15 at 14:39
  • So you'd put `self._attr = default_value` in `__init__`, then define a `@property` `attr` to access it in a read-only way. Or subclass a tuple, as the duplicate suggests. – jonrsharpe Aug 25 '15 at 14:40

0 Answers0