I would like a class whose instances return a value when called directly as if they inherit from int, float, str, etc. I imagine it’s overloading some function ???:
class A(object):
def __init__(self, value):
self.value = value
def somefunction(self):
if isintance(self.value, int):
return 5
else:
return 'something else'
def __???__(self):
return self.value
a = A(2)
a + 5 # 7
a.somefunction() # 5
a = A('foo')
a + "bar" # 'foobar'
a.somefunction() # 'something else'
I can’t simply subclass int as the value could be of different types.
Is this doable? Perhaps there’s a good reason that this can’t be done, but it’s late, and I can’t think of it. Thanks in advance.
Overriding
__getattr__won’t work because of metaclass confusion; the issue is that the relevant methods need to be in the instance’s class dict.If you’re happy with
valuebeing immutable, one way could be to override__new__and construct classes on demand:Note that this puts
Aaftertype(value)in the mro; this is necessary to stop__new__resulting in runaway recursion! If there’s methods onAthat should override those ontype(value), you can put them into the dict 3rd argument totype().