Created
July 12, 2020 10:41
-
-
Save anshajk/7fdbe7107be7d1b1c179461cbf946a90 to your computer and use it in GitHub Desktop.
@Property decorator example in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Using @property decorator | |
# Source - https://www.programiz.com/python-programming/property | |
class Celsius: | |
def __init__(self, temperature=0): | |
self.temperature = temperature | |
def to_fahrenheit(self): | |
return (self.temperature * 1.8) + 32 | |
@property | |
def temperature(self): | |
print("Getting value...") | |
return self._temperature | |
@temperature.setter | |
def temperature(self, value): | |
print("Setting value...") | |
if value < -273.15: | |
raise ValueError("Temperature below -273 is not possible") | |
self._temperature = value | |
# create an object | |
human = Celsius(37) | |
print(human.temperature) | |
print(human.to_fahrenheit()) | |
coldest_thing = Celsius(-300) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment