Meszias

Functional Temperature converter

Jun 25th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. class Temperature:
  2.     def __init__(self, temp, scale=None):
  3.         self.t = temp
  4.         self.scale = scale                
  5.         self.call_temp = {'c': {'c': self, 'f': self.celsius_to_fahrenheight, 'k': self.celsius_to_kelvin},
  6.                           'f': {'f': self, 'c': self.fahrenheight_to_celsius, 'k': self.fahrenheight_to_kelvin},
  7.                           'k': {'k': self, 'c': self.kelvin_to_celsius, 'f': self.kelvin_to_fahrenheight}}
  8.  
  9.     def celsius(t):
  10.         if isinstance(t, int):
  11.             return Temperature(t, 'c')
  12.         else:
  13.             return t.call_temp[t.scale]['c']()
  14.  
  15.     def fahrenheight(t):
  16.         if isinstance(t, int):
  17.             return Temperature(t, 'f')
  18.         else:
  19.             return t.call_temp[t.scale]['f']()
  20.  
  21.     def kelvin(t):
  22.         if isinstance(t, int):
  23.             return Temperature(t, 'k')
  24.         else:
  25.             return t.call_temp[t.scale]['k']()
  26.  
  27.     def __call__(self):
  28.         return self.t
  29.  
  30.     def celsius_to_fahrenheight(self):
  31.         f = (self.t)/5 + 32
  32.         return round(f,2)
  33.  
  34.     def celsius_to_kelvin(self):
  35.         k = self.t + 273
  36.         return round(k,2)
  37.  
  38.     def fahrenheight_to_celsius(self):
  39.         c = 5*(self.t-32)/9
  40.         return round(c,2)
  41.  
  42.     def fahrenheight_to_kelvin(self):
  43.         k = 5*(self.t-32)/9 + 273
  44.         return round(k,2)
  45.  
  46.     def kelvin_to_celsius(self):
  47.         c = self.t - 273
  48.         return round(c,2)
  49.  
  50.     def kelvin_to_fahrenheight(self):
  51.         f = 9*(self.t)/5 + 32            
  52.         return round(f,2)
  53.  
  54. t1 = Temperature(32)
  55. print(t1.celsius_to_kelvin())
  56.  
  57. print('C 32 to K', Temperature.celsius(32).kelvin())
  58. c1 = Temperature.celsius(30)
  59. print('C 30 to K', c1.kelvin())
  60. print('C 30 to F', c1.fahrenheight())
  61. print('C 30 itself', c1())
Add Comment
Please, Sign In to add comment