Jump to content

Object-Oriented Programming/Methods/Python3

From Wikiversity

main.py

[edit | edit source]
"""This program demonstrates use of the Temperature class."""

from temperature import Temperature

temperature = Temperature()
print(temperature.to_celsius(98.6))
print(temperature.to_fahrenheit(37))

temperature.py

[edit | edit source]
"""Temperature converter.

Examples:
    from temperature import Temperature
    
    temperature = Temperature()
    print(temperature.to_celsius(98.6))
    print(temperature.to_fahrenheit(37))

"""


class Temperature(object):
    """Supports Fahrenheit and Celius temperatures."""
    
    def to_celsius(self, fahrenheit):
        """Converts Fahrenheit temperature to Celsius.
    
        Args:
            fahrenheit (float): Fahrenheit temperature to be converted
    
        Returns:
            float: Celsius temperature
    
        """
        return (fahrenheit - 32) * 5 / 9
        
    
    def to_fahrenheit(self, celsius):
        """Converts Celsius temperature to Fahrenheit.
    
        Args:
            celsius (float): Celsius temperature to be converted
    
        Returns:
            float: Fahrenheit temperature
    
        """
        return celsius * 9 / 5 + 32

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.

See Also

[edit | edit source]