I have a value that is commonly used throughout my code in different units. For example. representing the size of the buffer in the amount of BYTES, but in many places referring to the size as KB or as MB (this is just an example, not my real use case).
For elegance and ease of use, I want to avoid explicit conversions (e.g. size/1024 or b_to_mb(size) ) because they are needed in many different places.
I thought I could achieve this with properties, which simplifies the conversion ( x.kb or x.mb ), and also causes the caller to not know the units of the stored actual value.
My code is as follows:
class BufferSize(int): @property def b(self): return int(self) @property def kb(self): return self.b / 1024 @property def mb(self): return self.kb / 1024
This works until I use arithmetic operators:
s = BufferSize(500000) s.kb => 488.28125
Is there a way to ensure that arithmetic operations preserve type? That is, in addition to redefining each of them?
Or maybe another and better way to solve the original problem?
operators python inheritance properties int
shx2
source share