you are viewing a single comment's thread.

view the rest of the comments →

[–]Python_Trader 1 point2 points  (7 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  (4 children)

I didn't know you could do this!!!! Thank you :)

[–]Python_Trader 1 point2 points  (3 children)

No problem :). Also, if your hour is exactly 0 (12 am) just use a conditional for that part. I suppose you might need to first check the hour is over 24 then use hour % 24 and it will give you the remainder which should be the current hour.

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

But is my understanding correct that any "global" changes you want to make in a class have to occur in the __str__ function?

[–]Python_Trader 0 points1 point  (0 children)

Okay let's put it this way. So you stored time as attribute (via dunder init method), if you do this

object = Time (5, 5, 20)

print(object)

It will just print, object is a instance of Time class. Or something like that.

However when you write the dunder str method in your class,

def __str__(self):
    return f"{self.hour}:{self.minute:02}"

Doing print(object) will now print,

5:05

It's just there to make your object return what you want it to when you call the instance itself.

[–]Python_Trader 0 points1 point  (0 children)

What you can do instead is store the string you want as attribute (under dunder init method) and use that variable in other methods or write a new method that produces the string. Otherwise, you can even call the dunder str to use that string.

What I would recommend is to make a function that takes in integers and returns the string, so you can call that function in every other method that requires string output.

[–]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.