存储@property函数

时间:2017-05-09 19:05:41

标签: python python-3.x properties

是否可以在变量中存储@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变量中?

1 个答案:

答案 0 :(得分:2)

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