I'd like for an instance of my class to always be treated as though it is one of its attributes, unless other attributes are specifically requested. For instance, suppose my class is:
class Value:
def __init__(self, value, description):
self.value = value
self.description = description
such that value
is a float and description
is a string. Now, I'd like for operations to always treat an instance of Value
as Instance.value
, unless Instance.description
is specifically requested.
I'm aware of two solutions to this. The first is to implement numeric emulation into the class in the following way:
def __add__(self, other):
return self.value + other
for every possible numerical operation. However, this seems unduly cumbersome -- what if someone wants to use a Value instance to multiply a list, and what about error messages, and all the other ways operating on a class instance instead of a basic float could go wrong? Do I really have to introduce class methods for every possible operational case?
The second solution is to redefine things in the following way:
class Value(float):
pass
value1 = Value(8.0)
value1.description = 'The first value'
value2 = Value(16.3)
value2.description = 'The second value'
...
...
Now, the instance simply is the float value, and the descriptions are hardcoded in. But this also seems cumbersome and incredibly un-Pythonic.
Am I missing a really simple method for this? Or some kind of boolean flag somewhere I can just flick on? It seems like it would be desirable often enough for Python to have a way.