I'm not really sure what a good title for this question would be, so i'll explain what I want to do.
I want to have a class, which can be instantiated in some way like so:
class Setting(int):
def __init__(self, value, description=None):
super(Setting, self).__init__(value)
self.description = description
max_memory = Setting(5, description="The maximum memory we can use")
print s + 5 # 10
print s.description # The maximum memory we can use
But then, I'd like this to work for all objects, so I can just have one class. So that I can have the object behave exactly as if it were the same as the underlying value
object, but just with the additional description
attribute.
I tried changing the above to:
class Setting(object):
def __init__(self, value, description=None):
type(value).__init__(value)
self.description = description
s = Setting(5)
print s + 5
print s.description
But now I get the error:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print s + 5
TypeError: unsupported operand type(s) for +: 'Setting' and 'int'
and if I look at dir(self)
, it does not seem to have run the initialiser for the class of value
.
Is it possible to do this?
I know i could just make a few different classes for the different types, but i'd rather only have the one and just have it be generic.
(yes i realise that if the object has a description
attribute it would be overwritten, i plan on using this only for the primitives, which is one of the reasons it's a problem in the first place since i can't just add attributes.)