I’m learning python useing How to think like a computer scientist: Learn python 3.
I’m learning OOP and have put together some code to answer a question in the book, but I feel like I should have done something else.
The code in question is incremental(), which the goal of is to increase the object’s values. Now my final solution was to make my method a copy of the initializer method and just add on the time right there.
This feels sloppy:
class MyTime:
def __init__(self, hrs=0, mins=0, secs=0,):
""" Create a new MyTime object initialized to hrs, mins, secs.
The values of mins and secs may be outside the range 0-59,
but the resulting MyTime object will be normalized.
"""
# calculate total seconds to represent
totalsecs = hrs*3600 + mins*60 + secs
self.hours = totalsecs // 3600 # split in h, m, s
leftoversecs = totalsecs % 3600
self.minutes = leftoversecs // 60
self.seconds = leftoversecs % 60
def incerment(self,t):
# increase the time by t amount
totalsecs = self.hours * 3600 + self.minutes * 60 + self.seconds + t
self.hours = totalsecs // 3600 # split in h, m, s
leftoversecs = totalsecs % 3600
self.minutes = leftoversecs // 60
self.seconds = leftoversecs % 60
t1 = MyTime(5,5,5)
t2 = MyTime(10,10,10)
t3 = MyTime(12,12,12)
print('before:',t1)
t1.incerment(100)
print('after:',t1)
So how about it?
Is there a way to clean this up?
That feeling like you should have done something else it’s beacuse
hours,minutes,secondsare properties.You don’t really need those values stored as attributes of your object, you just want to be able to access those values when you need.
Calling something like:
So, let’s rewrite your example using
property:Usage example:
I don’t know if you noticed but you don’t actually need the
incrementfunction anymore:I know that
propertymust be a little ahead of what you’re doing, but I thought it would have been worth an example.Edit: As Lattyware noticed there’s no need to make
totalsecsa property too.To quote his comment: The great thing about Python’s properties is you don’t need to turn everything into getters and setters to keep a consistent interface like you do in some languages.
There might be an advantage in setting
totalsecsas a property (read-only) only if for some reason you want to hide the internal implementation ofMyTime(obviously reintegrating theincrement()method).