1# Using @property decorator
2class Celsius:
3 def __init__(self, temperature=0):
4 self.temperature = temperature
5
6 def to_fahrenheit(self):
7 return (self.temperature * 1.8) + 32
8
9 @property
10 def temperature(self):
11 print("Getting value...")
12 return self._temperature
13
14 @temperature.setter
15 def temperature(self, value):
16 print("Setting value...")
17 if value < -273.15:
18 raise ValueError("Temperature below -273 is not possible")
19 self._temperature = value
20
21
22# create an object
23human = Celsius(37)
24
25print(human.temperature)
26
27print(human.to_fahrenheit())
28
29coldest_thing = Celsius(-300)
1# Making Getters and Setter methods
2class Celsius:
3 def __init__(self, temperature=0):
4 self.set_temperature(temperature)
5
6 def to_fahrenheit(self):
7 return (self.get_temperature() * 1.8) + 32
8
9 # getter method
10 def get_temperature(self):
11 return self._temperature
12
13 # setter method
14 def set_temperature(self, value):
15 if value < -273.15:
16 raise ValueError("Temperature below -273.15 is not possible.")
17 self._temperature = value
18
19
20# Create a new object, set_temperature() internally called by __init__
21human = Celsius(37)
22
23# Get the temperature attribute via a getter
24print(human.get_temperature())
25
26# Get the to_fahrenheit method, get_temperature() called by the method itself
27print(human.to_fahrenheit())
28
29# new constraint implementation
30human.set_temperature(-300)
31
32# Get the to_fahreheit method
33print(human.to_fahrenheit())
1# Basic method of setting and getting attributes in Python
2class Celsius:
3 def __init__(self, temperature=0):
4 self.temperature = temperature
5
6 def to_fahrenheit(self):
7 return (self.temperature * 1.8) + 32
8
9
10# Create a new object
11human = Celsius()
12
13# Set the temperature
14human.temperature = 37
15
16# Get the temperature attribute
17print(human.temperature)
18
19# Get the to_fahrenheit method
20print(human.to_fahrenheit())