Python property() Function
property() is a built-in function in Python used to create properties.
A property is a powerful mechanism that lets us execute code when an attribute is accessed; it is often used to implement computed attributes, data validation and other advanced features.
Word meaning: property 意为"属性",用于定义类的属性。
Basic syntax and parameters
Syntax format
property(fget=None, fset=None, fdel=None, doc=None)
Parameter Description
- Parameter fget(optional):
- Type: function
- Description: the function called when getting the attribute value.
- Parameter fset(optional):
- Type: function
- Description: the function called when setting the attribute value.
- Parameter fdel(optional):
- Type: function
- Description: the function called when deleting the attribute.
- Parameter doc(optional):
- Type: string
- Description: the docstring of the attribute.
Function description
- Return Value: Returns a property object.
- Feature: Makes attribute access look like an ordinary variable, while a function is actually executed.
Example
Example 1: basic usage
Example
class Circle:
def __init__(self, radius):
self.radius = radius
# Use property to create a computed attribute
def get_area(self):
"""Compute the area of the circle"""
return 3.14159 * self.radius ** 2
def set_radius(self, value):
"""Set the radius (validation can be added)"""
if value < 0:
raise ValueError("Radius cannot be negative")
self.radius = value
# Create the property
area = property(get_area, set_radius)
# Use it
c = Circle(5)
print(f"Radius: {c.radius}") # Output: Radius: 5
print(f"Area: {c.area}") # Output: Area: 78.53975
# Set the attribute
c.radius = 10
print(f"New area: {c.area}") # Output: New area: 314.159
# Validation
c.radius = -5 # An exception will be raised
def __init__(self, radius):
self.radius = radius
# Use property to create a computed attribute
def get_area(self):
"""Compute the area of the circle"""
return 3.14159 * self.radius ** 2
def set_radius(self, value):
"""Set the radius (validation can be added)"""
if value < 0:
raise ValueError("Radius cannot be negative")
self.radius = value
# Create the property
area = property(get_area, set_radius)
# Use it
c = Circle(5)
print(f"Radius: {c.radius}") # Output: Radius: 5
print(f"Area: {c.area}") # Output: Area: 78.53975
# Set the attribute
c.radius = 10
print(f"New area: {c.area}") # Output: New area: 314.159
# Validation
c.radius = -5 # An exception will be raised
Expected output:
半径: 5 面积: 78.53975 新面积: 314.159
Code analysis:
- Computed attributes can be defined through property.
- A setter can add data validation logic.
Example 2: using the @property decorator (recommended)
Example
class Student:
def __init__(self, name, score):
self.name = name
self._score = score
@property
def score(self):
"""Get the score"""
return self._score
@score.setter
def score(self, value):
"""Set the score (with validation)"""
if not 0 <= value <= 100:
raise ValueError("Score must be between 0 and 100")
self._score = value
@property
def grade(self):
"""Compute the grade from the score"""
if self._score >= 90:
return 'A'
elif self._score >= 80:
return 'B'
elif self._score >= 70:
return 'C'
elif self._score >= 60:
return 'D'
else:
return 'F'
# Use it
s = Student("Tom", 85)
print(s.name) # Output: Tom
print(s.score) # Output: 85
print(s.grade) # Output: B
s.score = 92 # Set the score
print(s.grade) # Output: A
s.score = 105 # An exception will be raised
def __init__(self, name, score):
self.name = name
self._score = score
@property
def score(self):
"""Get the score"""
return self._score
@score.setter
def score(self, value):
"""Set the score (with validation)"""
if not 0 <= value <= 100:
raise ValueError("Score must be between 0 and 100")
self._score = value
@property
def grade(self):
"""Compute the grade from the score"""
if self._score >= 90:
return 'A'
elif self._score >= 80:
return 'B'
elif self._score >= 70:
return 'C'
elif self._score >= 60:
return 'D'
else:
return 'F'
# Use it
s = Student("Tom", 85)
print(s.name) # Output: Tom
print(s.score) # Output: 85
print(s.grade) # Output: B
s.score = 92 # Set the score
print(s.grade) # Output: A
s.score = 105 # An exception will be raised
Expected output:
Tom 85 B A
Code analysis:
- The @property decorator is the more Pythonic way to write it.
- Getter, setter and deleter can all be defined.
Example 3: read-only attributes
Example
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
"""Read-only attribute"""
return self._name
# Without a setter, the attribute cannot be modified
p = Person("Tom")
print(p.name) # Output: Tom
# Trying to modify it raises an error (no setter)
# p.name = "Jack" # raises AttributeError
# Deleting it also raises an error
# del p.name # raises AttributeError
def __init__(self, name):
self._name = name
@property
def name(self):
"""Read-only attribute"""
return self._name
# Without a setter, the attribute cannot be modified
p = Person("Tom")
print(p.name) # Output: Tom
# Trying to modify it raises an error (no setter)
# p.name = "Jack" # raises AttributeError
# Deleting it also raises an error
# del p.name # raises AttributeError
Expected output:
Tom
Defining only a getter and no setter creates a read-only attribute.
Python3 built-in function