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.