It feels like you have to do something else, these are beacuse hours , minutes , seconds properties .
You really don't need these values ββstored as attributes of your object, you just want to have access to these values ββwhen you need to.
A call of something like:
>>> t1.hours 5
So rewrite your example with property :
class MyTime: def __init__(self, hrs=0, mins=0, secs=0): self.totalsecs = hrs*3600 + mins*60 + secs @property def hours(self): return self.totalsecs // 3600 @property def minutes(self): return self._get_leftoversecs() // 60 @property def seconds(self): return self._get_leftoversecs() % 60 def _get_leftoversecs(self): return self.totalsecs % 3600 def increment(self, t): self.totalsecs += t
Usage example:
>>> t1 = MyTime(5,5,5) >>> t1.hours 5 >>> t1.hours() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable >>> t1.seconds 5 >>> t1.totalsecs 18305 >>> t1.increment(10) >>> t1.seconds 15 >>> t1.totalsecs 18315
I don't know if you noticed, but you no longer need the increment function :
>>> t1.totalsecs += 10 >>> t1.totalsecs 18325
I know that property should be a little ahead of what you are doing, but I thought that would be a worthy example.
Edit: Since Lattyware has noticed that there is no need to create a totalsecs property.
To quote his comment: the wonderful thing about Python properties is that you donβt need to turn everything into getters and setters in order to maintain a consistent interface, as in some languages.
In setting up totalsecs may be an advantage in the quality of the property (read-only) only if for some reason you want to hide the internal implementation of MyTime (obviously by reintegrating the increment() method).