-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16_property.py
More file actions
39 lines (29 loc) · 995 Bytes
/
Copy path16_property.py
File metadata and controls
39 lines (29 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# property: attribute syntax with method behavior — the pythonic
# alternative to get_x()/set_x() pairs.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius # underscore: "internal, use the property"
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
# A derived, read-only attribute: computed on access, no setter at all
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(25)
print(t.celsius, t.fahrenheit) # reads look like plain attributes
t.celsius = 30 # goes through the setter
print(t.fahrenheit)
try:
t.celsius = -300 # setter validates
except ValueError as e:
print("rejected:", e)
try:
t.fahrenheit = 100 # no setter defined -> AttributeError
except AttributeError as e:
print("read-only:", e)