I want to create a class that wraps an int and allows some things not normally allowed with int types. Here is my code:
class tInt(int): def __add__(self, other): if type(other) == str: return str(self) + str(other) elif type(other) == int: return int(self) + other elif type(other) == float: return float(self) + float(other) else: return self + other a = tInt(2) print (a + "5") print ("5" + a) The output was:
25 Traceback (most recent call last): File "C:\example.py", line 14, in <module> print ("5" + a) TypeError: Can't convert 'tInt' object to str implicitly So, the first print statement ran nicely, and gave what I expected, but the second one gave an error. I think this is because the first one is using tInt.__add__ because a appeared before + "5" and the second one is using str.__add__ because "5" appeared first. I know this but I don't really know how to either force a.__add__ to be used or allow the tInt class to be represented as a string/int/etc. when a normal type appears before it in an operation.
elseclause will cause infinite recursion.self + otherwill callself.__add__(other)again.return NotImplementedinstead. This will instruct Python to either trytInt.__radd__(other)if it is defined, or to trytype(other).__add__(self)if not.