Welcome to the “Properties” tutorial!
Overview
Properties allow managed attribute access via getters/setters without changing the interface.
Example
class Celsius:
def __init__(self, temp):
self._temp = temp # internal
@property
def temp(self):
return self._temp
@temp.setter
def temp(self, value):
if value < -273.15:
raise ValueError("Below absolute zero!")
self._temp = value
c = Celsius(25)
print(c.temp) # 25
c.temp = 30
# c.temp = -300 # ValueError
Key Takeaways
- Use
@property
for getters. - Use
@<property>.setter
for setters. - Keep public API clean.
Happy coding!
Comments
Post a Comment