Programming Fundamentals/Objects/Python3: Difference between revisions
Jump to navigation
Jump to search
Content deleted Content added
Creating |
(No difference)
|
Revision as of 00:45, 5 March 2017
strings.py
# 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.
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(float(value))
@property
def fahrenheit(self):
return self._fahrenheit
@fahrenheit.setter
def fahrenheit(self, value):
self._fahrenheit = float(value)
self._celsius = self.to_celsius(float(value))
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 an instance of the Temperature class to convert Cesius
# and Fahrenheit temperatures.
def main():
temp = Temperature()
temp.celsius = 100
print("temp.celsius =", temp.celsius)
print("temp.fahrenheit =", temp.fahrenheit)
temp.fahrenheit = 100
print("temp.fahrenheit =", temp.fahrenheit)
print("temp.celsius =", temp.celsius)
main()
Try It
Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.
- GDB Online
- Ideone
- InterviewBit
- paiza.IO
- Programiz
- PythonTutor
- Python Fiddle
- repl.it
- RexTester
- Trinket
- TutorialsPoint