Intermediate Chapter 133 · 25 min read · Module 10: Object-Oriented Programming
Properties
- After this chapter you can create a read-only attribute with @property.
- You can add a setter that validates values before they are stored.
- You can build computed attributes that are always up to date.
- You can use a deleter and explain when it is useful.
- You can explain why properties let you change a class without breaking user code.
Imagine a class Circle with an attribute radius. Users write c.radius = 5 and read c.radius. This is simple and nice. Later you want to stop negative radius values. If you change radius into a method, every user must rewrite their code from c.radius to c.radius(). That is painful.
Python solves this with properties. A property looks like a normal attribute from the outside, but behind it runs a method. You can check values, compute results, or log changes, while users keep the simple dot syntax.
In this chapter you will learn the @property decorator, the setter and deleter, computed properties, and the design reasons to prefer properties over getter and setter methods like get_radius() and set_radius().
Why properties exist
In some languages programmers write getter and setter methods for every field, just in case they need checks later. In Python this is not needed. You start with a plain public attribute. If you later need control, you convert it into a property with the same name. All the old code that uses obj.attr keeps working. This is a big reason Python code stays short and readable.
A read-only property
Put @property above a method and Python lets you call it without brackets. The method runs each time you read the name. If you define only the getter, the attribute is read-only, and trying to assign to it raises AttributeError. This is a neat way to expose a value that should not be changed from outside.
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
@property
def area(self):
return self.w * self.h
r = Rectangle(4, 5)
print(r.area)
r.w = 10
print(r.area)
try:
r.area = 99
except AttributeError:
print("area is read-only")Notice that area is not stored anywhere. It is calculated every time from w and h, so it is never out of date. When you change w, the next read of area gives the new answer. Storing area in a separate attribute would force you to update it by hand and you could forget.
Setters and validation
To allow assignment, define a second method with the same name and decorate it with @name.setter. The setter receives the new value, so you can check it and raise ValueError if it is wrong. A common pattern is to keep the real data in a private-style attribute that starts with an underscore, such as _radius, and expose it through the public property radius.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("radius cannot be negative")
self._radius = value
c = Circle(3)
print(c.radius)
c.radius = 7
print(c.radius)
try:
c.radius = -1
except ValueError as e:
print("Error:", e)
print(c.radius)Look at __init__. It writes self.radius = radius, not self._radius = radius. This is on purpose, because the assignment goes through the setter, so even the first value is checked. If you wrote self._radius, you would skip validation for new objects.
@radius.setter needs the existing property named radius.Deleter and the property() function
A third decorator, @name.deleter, runs when you use del obj.name. It is rarely needed, but it can release a resource or reset a value. Under the hood the decorators call the built-in property(fget, fset, fdel, doc) function. You can use it directly, but the decorator form is cleaner and is what most code uses.
class Temperature:
def __init__(self, celsius=0):
self._c = 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
@celsius.deleter
def celsius(self):
print("resetting")
self._c = 0
@property
def fahrenheit(self):
return self._c * 9 / 5 + 32
t = Temperature(100)
print(t.fahrenheit)
t.celsius = 0
print(t.fahrenheit)
del t.celsius
print(t.celsius)Properties versus getter and setter methods
| Approach | Usage | Comment |
|---|---|---|
| Plain attribute | obj.x = 5 | Simplest, no checks |
| Getter/setter methods | obj.set_x(5) | Verbose, not Pythonic |
| Property | obj.x = 5 | Looks simple, can validate |
Properties give you the best of both worlds. The user sees a plain attribute, while you keep full control inside the class. Use them when you need validation, a computed value, a read-only value, or a hook that runs when a value changes. Do not use them for everything: if an attribute needs no rules, a plain attribute is better and faster.
One more point: a property that does slow work, such as reading a file, can surprise users because it looks like a cheap attribute. For heavy work, a normal method with a clear name is more honest. Also remember that a property lives on the class, so every object gets the same behaviour, while the data stays in each object.
Python syntax
class C:
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._xReal-world applications
- Validating user input such as age, price or radius before storing it
- Computed values like full_name, area or total that depend on other attributes
- Read-only identifiers such as an account number
- Keeping old code working after turning an attribute into checked logic
- Unit conversion views such as Celsius and Fahrenheit on one object
Common mistakes
Fix: Store it in a different name such as self._radius; using the same name makes the setter call itself forever and raises RecursionError.
Fix: Add a setter if assignment should be allowed, or keep it read-only on purpose and set the underlying value in __init__.
Fix: Assign through the public name (self.value = v) so validation also runs for the first value.
Fix: Read it as obj.name; adding () tries to call the returned value and usually raises TypeError.
Important tips
- Start with plain attributes and switch to properties only when you need them.
- Name the hidden attribute with a leading underscore.
- Raise ValueError or TypeError with a clear message in setters.
- Keep property code fast; move slow work into a method.
- Use a docstring in the getter to document the property.
Key points summary
- @property turns a method into an attribute-style read.
- @name.setter adds checked assignment.
- @name.deleter handles del obj.name.
- A getter-only property is read-only.
- Computed properties are always up to date.
Exam and interview points
- Properties are defined with the property built-in, usually through the decorator form.
- The setter decorator needs the getter to exist first and to have the same name.
- Assigning to a property without a setter raises AttributeError.
- Properties help keep the public interface stable when the inside changes.
Quick revision
- @property = method read like an attribute
- @x.setter = checked assignment
- @x.deleter = runs on del obj.x
- No setter = read-only
- Store data in _x, expose x
Frequently asked questions
Do I need getters and setters like in Java?
No. Use a public attribute first. If you later need checks, turn it into a property and no user code has to change.
Why does my setter cause RecursionError?
You probably wrote self.name = value inside the setter for name. That calls the setter again. Store into self._name instead.
Can a property be computed from other attributes?
Yes. A getter can return any calculation, such as self.w * self.h. It runs every time the property is read.
Is a property the same as a private attribute?
No. Python has no true private attributes. A property controls access and checks values, and the underscore name is only a hint to other programmers.
Can I make a property on one object only?
No. Properties belong to the class, so every object of the class uses them. Values are still stored per object.
Practise this chapter
18 practice questions Take the chapter quiz