Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python property() Function

Python property() Function

Python3 Built-in Functions Python3 built-in 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

Function description


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

Expected output:

半径: 5
面积: 78.53975
新面积: 314.159

Code analysis:

  1. Computed attributes can be defined through property.
  2. 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

Expected output:

Tom
85
B
A

Code analysis:

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

Expected output:

Tom

Defining only a getter and no setter creates a read-only attribute.


Python3 Built-in Functions Python3 built-in function