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 celsius
1class Temperature:
# The constructor runs when Temperature() is created
2 def __init__(self):
# The real value lives in _celsius (underscore: internal by convention)
3 self._celsius = 0
4
# @property makes celsius a getter: reading t.celsius calls this method
5 @property
6 def celsius(self):
# Return the stored value
7 return self._celsius
8
# @celsius.setter registers a setter under the same name
9 @celsius.setter
# Called for t.celsius = value (a good place for validation)
10 def celsius(self, value):
# Store the new value
11 self._celsius = value
12
# Create an instance; _celsius starts at 0
13t = Temperature()
# The assignment calls the setter, so _celsius becomes 25
14t.celsius = 25
# Reading calls the getter and prints 25
15print(t.celsius)

Output

25
Practice typing this code

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

More Python examples at level 4

← Python typing practice