Python property() Function
property()It is a built-in function in Python used to create properties.
property is a powerful mechanism that allows us to execute code when accessing attributes. It is often used to implement advanced features such as computed properties and data validation.
Word Definitions: 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 property value.
- Parameter fset(Optional):
- Type: Function
- Description: The function called when setting the property value.
- Parameter fdel(Optional):
- Type: Function
- Description: The function called when deleting the property.
- Parameter doc(Optional):
- Type: String
- Description: The docstring of the property.
Function Description
- Return Value: Returns a property object.
- Features: Makes property access look like a normal variable, but actually executes a function.
Examples
Example 1: Basic Usage
Example
class Circle:
def __init__(self, radius):
self.radius = radius
# Using property to create computed properties
def get_area(self):
"""Calculate the area of a 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 property
area = property(get_area, set_radius)
# Usage
c = Circle(5)
print(fRadius: {c.radius}) # Output: Radius: 5
print(fArea: {c.area}) # Output: Area: 78.53975
# Set property
c.radius = 10
print(fNew area: {c.area}) # Output: New area: 314.159
# Verify
c.radius = -5 # Will raise an exception
def __init__(self, radius):
self.radius = radius
# Using property to create computed properties
def get_area(self):
"""Calculate the area of a 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 property
area = property(get_area, set_radius)
# Usage
c = Circle(5)
print(fRadius: {c.radius}) # Output: Radius: 5
print(fArea: {c.area}) # Output: Area: 78.53975
# Set property
c.radius = 10
print(fNew area: {c.area}) # Output: New area: 314.159
# Verify
c.radius = -5 # Will raise an exception
Expected output:
半径: 5 面积: 78.53975 新面积: 314.159
Code explanation:
- With property, you can define computed properties.
- The setter can add data validation logic.
Example 2: Using @property Decorator (Recommended)
Example
class Student:
def __init__(self, name, score):
self.name = name
self._score = score
@property
def score(self):
"""Get score"""
return self._score
@score.setter
def score(self, value):
"""Set score (with validation)"""
if not 0 <= value <= 100:
raise ValueError(Score must be between 0 and 100)
self._score = value
@property
def grade(self):
"""Calculate grade based on 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'
# Usage
s = Student("Tom", 85)
print(s.name) # Output: Tom
print(s.score) # Output: 85
print(s.grade) # Output: B
s.score = 92 # Set score
print(s.grade) # Output: A
s.score = 105 # Will raise an exception
def __init__(self, name, score):
self.name = name
self._score = score
@property
def score(self):
"""Get score"""
return self._score
@score.setter
def score(self, value):
"""Set score (with validation)"""
if not 0 <= value <= 100:
raise ValueError(Score must be between 0 and 100)
self._score = value
@property
def grade(self):
"""Calculate grade based on 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'
# Usage
s = Student("Tom", 85)
print(s.name) # Output: Tom
print(s.score) # Output: 85
print(s.grade) # Output: B
s.score = 92 # Set score
print(s.grade) # Output: A
s.score = 105 # Will raise an exception
Expected output:
Tom 85 B A
Code explanation:
- The @property decorator is a more Pythonic way of writing it.
- You can define getter, setter, and deleter.
Example 3: Read-Only Property
Example
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
"""Read-only property"""
return self._name
# Without a setter, the property cannot be modified
p = Person("Tom")
print(p.name) # Output: Tom
# Trying to modify it will raise an error (no setter)
# p.name = "Jack" # will raise AttributeError
# Deleting it will also raise an error
# del p.name # will raise AttributeError
def __init__(self, name):
self._name = name
@property
def name(self):
"""Read-only property"""
return self._name
# Without a setter, the property cannot be modified
p = Person("Tom")
print(p.name) # Output: Tom
# Trying to modify it will raise an error (no setter)
# p.name = "Jack" # will raise AttributeError
# Deleting it will also raise an error
# del p.name # will raise AttributeError
Expected output:
Tom
By defining only a getter and no setter, you can create a read-only property.
Other Extensions
Python3 Built-in Functions