# temperature.py # Walker M. White (wmw2) # October 19, 2012 """Class to store the temperature. Very similar to the temperature converter at the start of the class. Maintains temperature in both farenheit and centrigrade, and makes sure the two values are consistent.""" class Temperature(object): """Instance represents a temperature value.""" _fahrenheit = 32.0 # Temperature in farenheit _centigrade = 0.0 # Temperature in centigrade @property def fahrenheit(self): """The temperature value in fahrenheit Setter keeps fahrenheit and centrigrade consistent. Invariant: Must be a float Must be equal 9*centigrade/5.0+32""" return self._fahrenheit @fahrenheit.setter def fahrenheit(self,value): assert type(value) == int or type(value) == float, `value`+' is not a number' self._fahrenheit = float(value) # Enforce the invariant # Enforce the SECOND part of the invariant self._centigrade = 5*(self._fahrenheit-32)/9.0 @property def centigrade(self): """The temperature value in centigrade Setter keeps fahrenheit and centrigrade consistent. Invariant: Must be a float Must be equal 5*(fahrenheit-32)/9.0""" return self._centigrade @centigrade.setter def centigrade(self,value): assert type(value) == int or type(value) == float, `value`+' is not a number' self._centigrade = float(value) # Enforce the invariant # Enforce the SECOND part of the invariant self._fahrenheit = 9*self._centigrade/5.0+32 def __init__(self, fahrenheit=None,centigrade=None): """Constructor: Creates a temperature with the given fahrenheit or centigrade value. Preconditions: fahrenheit and centigrade are both either a number or None Both farenheit and centrigrade cannot be none.""" assert fahrenheit is None or centigrade is None, 'You can only have one temparature parameter' if not fahrenheit is None: self.fahrenheit = fahrenheit # Property takes care of other preconditions if not centigrade is None: self.centigrade = centigrade # Property takes care of other preconditions def __repr__(self): """Returns: Unambiguous tring representation of this temperature""" return str(self.__class__) + str(self) def __str__(self): """Returns: String representation of this temperature""" return str(self.fahrenheit) + ' F (' + str(self.centigrade) + ' C)' def __eq__(self,other): """Returns: True if other is an equal temperature.""" if not instanceof(other,Temperature): return false # Compare floats by checking if the difference is small. return abs(other.fahrenheit-self.fahrenheit) < 1e-12