Assign temperature value in one scale and you have it available in others as respective attributes. Kelvin, Celsius, Fahrenheit, and Rankine are supported (k, c, f, r attributes).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class Temperature(object):
equations = {'c': (1.0, 0.0, -273.15), 'f': (1.8, -273.15, 32.0),
'r': (1.8, 0.0, 0.0)}
def __init__(self, k=0.0, **kwargs):
self.k = k
for k in kwargs:
if k in ('c', 'f', 'r'):
setattr(self, k, kwargs[k])
break
def __getattr__(self, name):
if name in self.equations:
eq = self.equations[name]
return (self.k + eq[1]) * eq[0] + eq[2]
else:
return object.__getattribute__(self, name)
def __setattr__(self, name, value):
if name in self.equations:
eq = self.equations[name]
self.k = (value - eq[2]) / eq[0] - eq[1]
else:
object.__setattr__(self, name, value)
def __str__(self):
return "%g K" % self.k
def __repr__(self):
return "Temperature(%g)" % self.k
|
This was spurred by another temperature-related recipe. I've seen a similar class on SourceForge snippets, but the service seems to be broken now, so I patched-up this one.
Tags: algorithms
Alternatively. If you don't like to have magic numbers sprinkled through your code...
Good idea. Thanks. Added that, plus a couple of optimizations. Dropped get/set methods.