dontoronto
dontoronto

Reputation: 97

python why does it call __str__ instead of __repr__ and why is the print(obj) not working and throws exception

I have a litte problem because whenever i run the code print(obj) in the try/except part it throws an exception. i followed it with the debugging tool and it jumps right in the str method but i coded the str methode just for testing. Normally i thought it would jump in the repr method for normal class calls. The code breaks right in the return command of the str() method. I just wanted to change the output of the time.time_struct class because i need the string and the attribute represenation. the print commands ar just for displaying the results, the block in the init statement works but in the try/Except block it doesnt. Does anyone have an idea?

import time

class timeSelf():

def __init__(self,str):
    self.obj = time.strptime(str, "%H:%M")
    print(self.obj.tm_hour)
    print(type(self.obj))
def __repr__(self):
    return "" + self.obj.tm_hour + ":" + self.obj.tm_min

def __str__(self):
    return "" + self.obj.tm_hour + ":" + self.obj.tm_min

if __name__ == "__main__":
str= "16:54"
try:
    obj = timeSelf(str)
    print(obj)
    print(type(obj))
    print(type(obj.tm_hour))
except Exception:
    print("stuff happened")
    pass

Upvotes: 0

Views: 485

Answers (1)

chepner
chepner

Reputation: 532093

If you hadn't caught the exception (or if you re-raised it to see what you had caught), you would see the problem is with your definitions of __str__ and __repr__. You are attempting to combine int and "" values with +, and no automatic conversion of int to str occurs there.

Traceback (most recent call last):
  File "tmp.py", line 19, in <module>
    print(obj)
  File "tmp.py", line 13, in __str__
    return "" + self.obj.tm_hour + ":" + self.obj.tm_min
TypeError: can only concatenate str (not "int") to str

You have to be explicit:

return "" + str(self.obj.tm_hour) + ":" + str(self.obj.tm_min)

or more simply:

return f"{self.obj.tm_hour}:{self.obj.tm_min}"

f-strings do call __str__ as necessary to convert the value inside {...} to a str.

Upvotes: 2

Related Questions