You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Python property对象的fget、fset、fdel属性?

如何从Python的property对象中获取fget、fset和fdel属性

在Python中,property对象本身就直接暴露了fget、fset和fdel这三个属性,你可以直接通过点语法访问它们。

示例1:传统方式定义的property

class MyClass:
    def __init__(self):
        self._x = 0

    def get_x(self):
        return self._x

    def set_x(self, value):
        self._x = value

    def del_x(self):
        del self._x

    x = property(get_x, set_x, del_x)

# 获取property对象
prop = MyClass.x

# 直接访问三个属性
print(prop.fget)  # 输出: <function MyClass.get_x at 0x...>
print(prop.fset)  # 输出: <function MyClass.set_x at 0x...>
print(prop.fdel)  # 输出: <function MyClass.del_x at 0x...>

示例2:装饰器方式定义的property

class MyClass:
    def __init__(self):
        self._x = 0

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

prop = MyClass.x
print(prop.fget)  # 对应@property装饰的方法
print(prop.fset)  # 对应@x.setter装饰的方法
print(prop.fdel)  # 对应@x.deleter装饰的方法

注意事项

如果property未定义某个操作方法(比如只声明了getter,未定义setter和deleter),对应的属性会返回None:

class MyClass:
    @property
    def x(self):
        return 0

prop = MyClass.x
print(prop.fset)  # 输出: None
print(prop.fdel)  # 输出: None

内容的提问来源于stack exchange,提问作者Pavel Demeshkevich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:05:05