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?