I am trying to emulate the built-in hex()
method for custom object using magic method __hex__
.I am getting the following error which I'm not able to figure out why its doing so.
class Point:
def __init__(self,x):
self.x= x
def __hex__(self):
return hex(self.x)
p1=Point(10)
print(hex(p1))
TypeError: 'point' object cannot be interpreted as an integer
but when i call hex
method using p1.__hex__()
instead of hex(p1)
, the code works fine
>>>print(p1.__hex__())
0xa
can you explain why this is happening?
All you need to do is make an __index__
method:
class Point:
def __init__(self, x):
self.x = x
def __index__(self):
return self.x