【问题标题】:Storing @property functions存储@property 函数
【发布时间】:2017-05-09 19:05:40
【问题描述】:

是否可以在变量中存储@property 函数?

假设我们有以下代码:

class I:
  def __init__(self):
    self.i = 0

  def get_i(self):
    return self.i

a = I()

f_i = a.get_i

print(f_i())

a.i = 3

print(f_i())

我将函数 get_i 保存在一个变量中并使用它。输出如预期:

0
3

现在让我们看一下相同的代码,但这次使用@property 函数:

class I:
  def __init__(self):
    self.i = 0

  @property
  def get_i(self):
    return self.i

a = I()

f_i = a.get_i

现在a.get_i 不再是函数(它的值是 0)。有没有办法将函数仍然存储在 f_i 变量中?

【问题讨论】:

    标签: python python-3.x properties


    【解决方案1】:

    property 的全部意义在于它在访问时被调用。你必须绕过descriptor protocol 来防止这种情况发生。

    您可以通过访问类上的property 对象来做到这一点:

    f_i = I.get_i
    

    然后稍后将其绑定到一个实例:

    print(f_i.__get__(a))
    

    或者您可以访问属性对象上的fget getter 函数,将其绑定到a 以创建绑定方法,并将结果存储起来以供以后调用:

    f_i = I.get_i.fget.__get__(a) 
    print(f_i())
    

    访问类上的属性仍会调用描述符协议,但在这种情况下property.__get__会返回属性本身。

    演示:

    >>> a = I()
    >>> I.get_i
    <property object at 0x10efceb88>
    >>> I.get_i.__get__(a)
    0
    >>> I.get_i.fget
    <function I.get_i at 0x10efc3048>
    >>> I.get_i.fget.__get__(a)
    <bound method I.get_i of <__main__.I object at 0x10efd32e8>>
    >>> I.get_i.fget.__get__(a)()
    0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多