Python class property definition and usage examples 2025
Added 'class' and 'examples' for clarity and specificity, and included the year to ensure the results are current and relevant.
In Python, properties provide a convenient way to manage the attributes of a class, allowing for controlled access and modification. This feature enhances encapsulation by letting you define getters, setters, and deleters that interact with the class attributes indirectly, thereby allowing you to enforce constraints, validation, and additional logic without changing the way the attributes are accessed.
A property in Python is a special attribute that uses the @property decorator. It allows you to define methods in a class that can be accessed like attributes, yet they can encapsulate complex behavior such as validation, logging, or computation, essentially acting as managed attributes.
To define a property, you typically start with a class that may look something like this:
class Circle:
def __init__(self, radius):
self._radius = radius # Internal attribute
@property
def radius(self):
"""Get the radius of the circle"""
return self._radius
@radius.setter
def radius(self, value):
"""Set the radius of the circle with validation"""
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
"""Calculate the area of the circle"""
import math
return math.pi * (self._radius ** 2)
# Usage
circle = Circle(5)
print(circle.radius) # Accessing the radius via the getter
print(circle.area) # Accessing the area, no setter needed
circle.radius = 10 # Using the setter
print(circle.area) # Area recalculated with the new radius
__init__ method initializes the internal attribute _radius.@property decorator allows the radius function to be accessed like an attribute.@radius.setter decorator defines a setter for the radius that includes validation to ensure the radius cannot be negative.area property is a read-only attribute calculated based on the radius.Properties are particularly useful in scenarios where attributes require validation or when you want to calculate values dynamically. Here’s another example:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
# Usage
person = Person("Alice", 30)
print(person.age) # 30
try:
person.age = -5 # This will raise ValueError
except ValueError as e:
print(e) # Output: Age cannot be negative
For more detailed examples and explanations, you can take a look at the articles on Real Python and Mimo.