Jul-22-2020, 05:35 PM
Hey guys,
I am currently learning class special methods.
There's my class:
I am expecting if isinstance(other, Time_Cal) return False so, the code can raise the TypeError.
However, for some reasons, it always return True and enter the next step logic which will cause uncatched exceptions.
Is anyone who can help me out? Thanks
I am currently learning class special methods.
There's my class:
class Time_Cal: def __init__(self, hour=0, minute=0, seg=0): self.hour = hour self.minute = minute self.seg = seg def __add__(self, other): if isinstance(other, Time_Cal): return self.__add_sub(other, "addition") else: raise TypeError("The object is not Time_Cal") def __str__(self): return str(self.hour) + ":" + str(self.minute) + ":" + str(self.seg)There's the code in main:
from myTime import Time_Cal time1 = Time_Cal(5, 45, 12) time2 = Time_Cal(7, 50, 24) print("The sum of Time1 and Time2:", str(time1 + time2))The logic actually works, however, I am now testing the code what if I create my object something like this:
time1 = Time_Cal(5, 45, 12) time2 = Time_Cal(7, 50, "24")So time2 is not a Time_Cal object (because one of the argument is not int anymore.)
I am expecting if isinstance(other, Time_Cal) return False so, the code can raise the TypeError.
However, for some reasons, it always return True and enter the next step logic which will cause uncatched exceptions.
Is anyone who can help me out? Thanks