Welcome, guest | Sign In | My Account | Store | Cart

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).

Python, 30 lines
 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.

2 comments

Andreas Nilsson 19 years, 9 months ago  # | flag

Alternatively. If you don't like to have magic numbers sprinkled through your code...

class Temperature(object):
equations = {'r': [1.8, 0.0, 0.0], 'c': [1.0, 0.0, -273.15], 'f': [1.8, -273.15, 32.0]}

    def __init__(self):
        self.k = 0

    def __str__(self):
        return "%g K" % self.k

    def __repr__(self):
        return "Temperature(%g K)" % self.k

    def __getattr__(self, name):
        if self.equations.has_key(name):
            return (self.k + self.equations[name][1]) * self.equations[name][0] + self.equations[name][2]
        else:
            return object.__getattr__(self, name)

    def __setattr__(self, name, value):
        if self.equations.has_key(name):
            self.k = (value - self.equations[name][2]) / self.equations[name][0] - self.equations[name][1]
        else:
            object.__setattr__(self, name, value)
Artur de Sousa Rocha (author) 19 years, 9 months ago  # | flag

Good idea. Thanks. Added that, plus a couple of optimizations. Dropped get/set methods.

Created by Artur de Sousa Rocha on Mon, 12 Jul 2004 (PSF)
Python recipes (4591)
Artur de Sousa Rocha's recipes (8)

Required Modules

  • (none specified)

Other Information and Tasks