Property Decorator in Python

Level 4162 keystrokes

This uses the @property decorator to create a computed attribute that acts like a regular attribute.

Python code

# Define a Circle class
1class Circle:
# The constructor receives the radius
2 def __init__(self, radius):
# Store it in _radius (underscore: internal by convention)
3 self._radius = radius
4
# @property lets area be read like an attribute
5 @property
6 def area(self):
# Compute πr² with π approximated as 3.14
7 return 3.14 * self._radius ** 2
8
# Create a circle with radius 5
9c = Circle(5)
# c.area has no parentheses: 3.14 * 25 = 78.5
10print(f"Area: {c.area}")

Output

Area: 78.5
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.

  • _× 6
  • :× 4
  • .× 4
  • (× 4
  • )× 4
  • *× 3
  • "× 2
  • =× 2
  • ,× 1
  • {× 1

More Python examples at level 4

← Python typing practice