Python Examples

Dave Braunschweig

Objects

# This class converts temperature between Celsius and Fahrenheit.
# It may be used by assigning a value to either Celsius or Fahrenheit 
# and then retrieving the other value, or by calling the to_celsius or
# to_fahrenheit methods directly.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Python_Programming

class Temperature:
    _celsius = None
    _fahrenheit = None
    
    @property
    def celsius(self):
        return self._celsius 

    @celsius.setter
    def celsius(self, value):
        self._celsius = float(value)
        self._fahrenheit = self.to_fahrenheit(self._celsius)
            
    @property
    def fahrenheit(self):
        return self._fahrenheit 
    
    @fahrenheit.setter
    def fahrenheit(self, value):
        self._fahrenheit = float(value)
        self._celsius = self.to_celsius(self._fahrenheit)

    def __init__(self, celsius=None, fahrenheit=None):
        if celsius != None:
            self._celsius = celsius
            self._fahrenheit = self.to_fahrenheit(celsius)
        if fahrenheit != None:
            self._fahrenheit = fahrenheit
            self._celsius = self.to_celsius(fahrenheit)

    def to_celsius(self, fahrenheit):
        return (fahrenheit - 32) * 5 / 9
        
    def to_fahrenheit(self, celsius):
        return celsius * 9 / 5 + 32


# This program creates instances of the Temperature class to convert Cesius 
# and Fahrenheit temperatures.

def main():
    temp1 = Temperature(celsius=0)
    print("temp1.celsius =", temp1.celsius)
    print("temp1.fahrenheit =", temp1.fahrenheit)
    print("")
    
    temp1.celsius = 100
    print("temp1.celsius =", temp1.celsius)
    print("temp1.fahrenheit =", temp1.fahrenheit)
    print("")
    
    temp2 = Temperature(fahrenheit=0)
    print("temp2.fahrenheit =", temp2.fahrenheit)
    print("temp2.celsius =", temp2.celsius)
    print("")

    temp2.fahrenheit = 100
    print("temp2.fahrenheit =", temp2.fahrenheit)
    print("temp2.celsius =", temp2.celsius)

main()

Output

temp1.celsius = 0
temp1.fahrenheit = 32.0

temp1.celsius = 100.0
temp1.fahrenheit = 212.0

temp2.fahrenheit = 0
temp2.celsius = -17.77777777777778

temp2.fahrenheit = 100.0
temp2.celsius = 37.77777777777778

References

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Authors and Contributors is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book