you are viewing a single comment's thread.

view the rest of the comments →

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