Property Getter and Setter in Python
Level 4223 keystrokes
This shows property getter and setter decorators. Properties allow controlled access to instance attributes.
Python code
# Define a class with a managed attribute celsius1class Temperature: # The constructor runs when Temperature() is created2 def __init__(self): # The real value lives in _celsius (underscore: internal by convention)3 self._celsius = 04 # @property makes celsius a getter: reading t.celsius calls this method5 @property6 def celsius(self): # Return the stored value7 return self._celsius8 # @celsius.setter registers a setter under the same name9 @celsius.setter # Called for t.celsius = value (a good place for validation)10 def celsius(self, value): # Store the new value11 self._celsius = value12 # Create an instance; _celsius starts at 013t = Temperature()# The assignment calls the setter, so _celsius becomes 2514t.celsius = 25# Reading calls the getter and prints 2515print(t.celsius)Output
25
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 7.× 6(× 5)× 5:× 4=× 4@× 2,× 1