Skip to content

Module 11 · Object-Oriented Programming — topic 23 of 25

Properties

Attribute-style access with method logic: @property getters, setters with validation, computed and read-only attributes, and adding properties later without changing callers.

Beginner 10 min read·Lesson 180 of 306 in Python Programming

Learning objectives

  • Create computed attributes with @property
  • Validate assignments with a setter
  • Make attributes read-only

Definition

A property is a managed attribute defined with the @property decorator. Reading obj.name calls the getter method, and assigning obj.name = value calls the setter if one is defined with @name.setter.

Introduction

In Java you'd write getAge() and setAge(). In Python you write p.age and p.age = 31 — and if validation is needed later, a property adds it without changing a single caller.

Why it matters

Properties keep classes simple: start with plain attributes, and add logic only when needed. Callers never notice the change.

Detailed explanation

Decorate a method with @property to make it readable as an attribute: c.area instead of c.area().

Add a setter with @name.setter on a method of the same name; it receives the assigned value.

The real value is usually stored in a 'backing' attribute with an underscore, such as self._age.

Assigning self.age = value inside __init__ goes through the setter, so construction is validated too.

A property without a setter is read-only: assignment raises AttributeError.

Computed properties derive their value from other attributes, so they are always up to date.

Keep property getters fast and free of side effects; slow or surprising work belongs in an ordinary method.

Syntax

Python
class Person:
def __init__(self, age):
self.age = age # uses the setter
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not 0 <= value <= 150:
raise ValueError("invalid age")
self._age = value
  • @property for the getter.
  • @name.setter for assignment.
  • Store the value in _name.

Code examples

A computed property

Python
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return round(3.14159 * self.radius ** 2, 2)
c = Circle(2)
print(c.area)
c.radius = 3
print(c.area)
Output
12.57
28.27

Validating with a setter

Python
class Person:
def __init__(self, age):
self.age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not 0 <= value <= 150:
raise ValueError(f"invalid age: {value}")
self._age = value
p = Person(30)
p.age = 31
print(p.age)
for bad in (-5, 200):
try:
p.age = bad
except ValueError as e:
print(e)
Output
31
invalid age: -5
invalid age: 200

More examples

Two views of one value

Python
class Temperature:
def __init__(self, celsius=0):
self.celsius = celsius
@property
def celsius(self):
return self._c
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._c = value
@property
def fahrenheit(self):
return round(self._c * 9 / 5 + 32, 2)
@fahrenheit.setter
def fahrenheit(self, f):
self.celsius = (f - 32) * 5 / 9
t = Temperature(25)
print(t.celsius, t.fahrenheit)
t.fahrenheit = 212
print(t.celsius, t.fahrenheit)
try:
t.fahrenheit = -500
except ValueError as e:
print(e, "| still", t.celsius)
Output
25 77.0
100.0 212.0
below absolute zero | still 100.0

Step-by-step explanation

  • Only _c is stored; fahrenheit is calculated from it.
  • Setting fahrenheit converts the value and assigns celsius, so the Celsius validation still applies.
  • An invalid Fahrenheit value is rejected and the stored temperature is unchanged.

Expected output

Running “Two views of one value” prints exactly:

TextOutput
25 77.0
100.0 212.0
below absolute zero | still 100.0

Practical applications

  • pathlib.Path.name and .suffix are read-only properties.
  • ORM models use properties for derived fields such as full_name.

Best practices

  • Start with plain attributes; add properties when logic is needed.
  • Store data in an underscore attribute.
  • Keep getters cheap and side-effect free.

Common mistakes

Recursion in the setter

Avoid

@age.setter
def age(self, value):
self.age = value

Prefer

@age.setter
def age(self, value):
self._age = value

Assigning self.age inside the setter calls the setter again forever (RecursionError).

Calling a property like a method

Avoid

c.area()

Prefer

c.area

The property already returns the value; calling it tries to call a number.

Important notes

  • functools.cached_property computes a value once and stores it, useful for expensive derived data.

Key takeaways

  • @property makes a method read like an attribute.
  • @name.setter validates assignment.
  • No setter means read-only.

Try it yourself

  1. 1
    Give a Rectangle width and height properties that reject non-positive values, plus a read-only area.
  2. 2
    Add a full_name property with a setter that splits the name into first and last.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat happens on t.f = 50 if f is a property with no setter?
Practise this topic