Python property(): Syntax, Usage, and Examples
The property() function in Python lets you manage how class attributes are accessed and modified. Instead of calling explicit getter or setter methods, you can create attributes that behave like regular variables but include custom logic behind the scenes. This gives your code clarity without losing control.
How to Use the Python property() Function
You can create a property using either the property() function or the @property decorator.
Syntax Using the property() Function
python
class Example:
def __init__(self):
self._value = 0
def get_value(self):
return self._value
def set_value(self, new_value):
self._value = new_value
value = property(get_value, set_value)
This defines a value attribute with custom getter and setter methods. The property() call ties them together.
Syntax Using the @property Decorator
python
class Example:
def __init__(self):
self._value = 0
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value
This approach is more common in modern Python and easier to read.
When to Use property() in Python
Use the Python property function when you:
- Want to control access to a class attribute without changing how it’s used.
- Need to run logic when an attribute is read or updated.
- Prefer cleaner syntax over calling getter/setter methods.
- Want to validate or transform values before storing them.
These cases are common in applications that rely on clean interfaces or enforce strict rules for internal state.
Examples of Python Property in Action
Simple Getter and Setter
python
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
if not new_name:
raise ValueError("Name cannot be empty")
self._name = new_name
user = Person("Maya")
print(user.name) # Output: Maya
user.name = "Sam"
This pattern lets you treat name like a variable, but with validation baked in.
Read-Only Property
python
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9/5 + 32
t = Temperature(0)
print(t.fahrenheit) # Output: 32.0
You get a derived value as a regular attribute without exposing a setter.
Write-Only Property
python
class PasswordManager:
def __init__(self):
self._hashed_password = None
@property
def password(self):
raise AttributeError("Password is write-only")
@password.setter
def password(self, plain_text):
self._hashed_password = hash(plain_text)
manager = PasswordManager()
manager.password = "mysecret"
This is useful when storing sensitive data like passwords.
Learn More About Python Properties
property() vs property decorator
Both property() and @property achieve the same goal. The decorator syntax is preferred for readability. The manual property() function is useful when you’re defining multiple properties dynamically or want more control.
python
# Using property()
class Demo:
def __init__(self):
self._value = 0
def get_value(self):
return self._value
def set_value(self, val):
self._value = val
value = property(get_value, set_value)
Python Property Setter and Getter Naming
Keep getter/setter method names consistent. Using the same name across the property, getter, and setter maintains clarity:
python
@property
def count(self):
return self._count
@count.setter
def count(self, value):
self._count = value
Avoid unrelated names like get_count() and modify_count() unless you’re using the property() function explicitly.
Cached Property in Python
You can improve performance with functools.cached_property. It caches the result of a method the first time it’s accessed:
python
from functools import cached_property
class Circle:
def __init__(self, radius):
self.radius = radius
@cached_property
def area(self):
print("Calculating area...")
return 3.14 * self.radius ** 2
c = Circle(5)
print(c.area) # Calculates once
print(c.area) # Uses cached result
This is useful for expensive calculations that don’t need to rerun unless the state changes.
Abstract Property in Python
You can define abstract properties in base classes using the abc module:
python
from abc import ABC, abstractmethod
class Animal(ABC):
@property
@abstractmethod
def sound(self):
pass
Subclasses must implement the sound property, ensuring a consistent interface.
Python Properties in Data Classes
With Python 3.8+, data classes can use properties too:
python
from dataclasses import dataclass
@dataclass
class Item:
_price: float
@property
def price(self):
return round(self._price, 2)
item = Item(12.3456)
print(item.price) # Output: 12.35
This allows formatting, conversion, or validation on access.
Check If Property Exists in Python
To see if an attribute is a property, use:
python
isinstance(type(obj).__dict__["attr_name"], property)
Or, catch an AttributeError when accessing properties that aren’t set.
Real-World Use Cases
Form Validation
When building forms, properties help you validate data before saving it:
python
class Form:
def __init__(self):
self._email = ""
@property
def email(self):
return self._email
@email.setter
def email(self, value):
if "@" not in value:
raise ValueError("Invalid email")
self._email = value
Data Transformation
Transform and store data behind the scenes without changing the public interface:
python
class Order:
def __init__(self, amount):
self._amount = amount
@property
def tax(self):
return self._amount * 0.2
Simplify APIs
Libraries use properties to provide simpler interfaces without exposing internal methods.
Best Practices for Using Python Properties
- Use properties for clean syntax, not just because you can.
- Only add logic when you need to validate, transform, or compute on access.
- Keep properties fast—don’t hide long computations behind them unless cached.
- Combine with
@classmethodor@staticmethodonly when it makes sense.
The Python property function lets you create smart attributes that look like variables but act like functions. Whether you want to add validation, lazy calculations, or restrict access, properties give you the flexibility to keep your class interface clean and intuitive.
You can use the Python property decorator for readability, or stick with the base function if you’re building classes dynamically. Either way, understanding properties in Python helps you write more maintainable, professional code.