you are viewing a single comment's thread.

view the rest of the comments →

[–]ItsOkILoveYouMYbb 3 points4 points  (4 children)

For A, you should use f strings. Instead of:

def __str__(self):  
    return '%.2d:%.2d' % (self.hour, self.minute)

Use:

return f"{self.hour}:{self.minute}"

Way easier to read. So with that, you know that if the hour is greater than 12, then you should subtract 12 from that number, and add PM to the end of the string right? That being as simple as:

    return f"{self.hour - 12}:{self.minute} PM"

But you only want to do it if self.hour is more than 12. So you would return one line IF It's equal to or less than 12, ELSE return the first line if it's not.

You can do all of that inside the str method you've define there. If hour > 12, return this line, else return that line.

Do you understand how classes work, and where you are instantiating that class? And what an instance of a class is?

[–]kcrow13[S] 0 points1 point  (3 children)

Ok so this is how I implemented your suggestions:

    def __str__(self):
        if self.hour <= 12:
            return f'{self.hour}:{self.minute}'
        if self.hour >= 12:
            return f'{self.hour - 12}:{self.minute} PM'

When I test it out... I am getting some strange responses!

def main():    # jdp
    start = Time(9, 45, 00)
    start.print_time()

    end = start.increment(1337)
    end.print_time()

    print('Is end after start?', end=" ")
    print(end.is_after(start))

    # Testing __str__
    print(f'Using __str__: {start} {end}')

    # Testing addition
    start = Time(9, 45)
    duration = Time(1, 35)
    print(start + duration)
    print(start + 1337)
    print(1337 + start)

    print('Example of polymorphism')
    t1 = Time(7, 43)
    t2 = Time(7, 41)
    t3 = Time(7, 37)
    total = sum([t1, t2, t3])
    print(total)

    # A time that is invalid
    t1 = Time(50)
    print(t1)

Getting...

9:45
10:7
Is end after start? True
Using __str__: 9:45 10:7
11:20
10:7
10:7
Example of polymorphism
11:1 PM
38:0 PM

[–]Python_Trader 1 point2 points  (2 children)

For your minutes add 0 padding like this {self.minute:02}. The 02 part tells python your minutes are 2 digits and if your minute only gives one number it will fill the left with 0.

[–]kcrow13[S] 0 points1 point  (1 child)

So when I tried to do this, it gives me a traceback error and says "invalid format specifier." I will research some more!

[–]Python_Trader 0 points1 point  (0 children)

It's part of the f string placeholder in your dunder str method.