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

如何将@property装饰的函数作为一等函数绑定使用?

可行,但你需要先理解@property的工作机制:当你访问a_instance.x时,Python会自动调用对应的getter函数并返回结果,所以你拿到的是5而不是函数本身。要获取被@property装饰的原始函数,得从类的属性入手。

A.x是一个property对象,它的fget属性就是你用@property装饰的原始getter函数。这个函数是一等函数,可以被绑定到其他实例上使用。

方法一:动态给实例添加@property(实现属性式访问)

如果你希望像访问普通@property那样直接用b_instance.x获取结果,可以通过动态创建子类的方式实现,不会影响原B类的其他实例:

import types

class A:
    _x = 5
    
    @property
    def x(self):
        return self._x

class B:
   _x = 12


a_instance = A()
b_instance = B()

# 获取A类中x属性的原始getter函数
original_getter = A.x.fget

# 创建B的临时子类,添加x的property
class BWithX(B):
    x = property(original_getter)

# 修改b_instance的类为临时子类
b_instance.__class__ = BWithX

assert b_instance.x == 12  # 验证通过

方法二:直接绑定getter函数(作为一等函数传递)

如果你只是想把getter函数作为一等函数传递、存储,之后再调用,可以直接绑定到目标实例:

import types

# 获取原始getter函数
getter_func = A.x.fget

# 将函数绑定到b_instance,得到绑定方法
bound_getter = types.MethodType(getter_func, b_instance)

# 调用绑定方法即可得到目标值
assert bound_getter() == 12

关键总结

  • 访问实例的@property属性(如a_instance.x)时,必然会执行getter并返回结果,无法直接拿到函数本身。
  • 要获取原始getter函数,必须从类的属性(A.x)中取出property对象的fget属性。
  • 这个原始函数是一等函数,可以被绑定、传递,甚至重新包装为其他类的@property。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:55:27