Python类@property:使用setter但避开getter?

2024-05-14 00:47:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在python类中,@property是一个很好的装饰器,它避免使用显式的setter和getter函数。然而,它的开销是“经典”类函数的2-5倍。在我的例子中,这在设置属性的情况下是很好的,与设置时需要进行的处理相比,开销是微不足道的。

但是,在获取属性时不需要处理。它总是“归还自己的财产”。有没有一种优雅的方法可以使用setter而不使用getter,而不需要使用不同的内部变量?

为了说明这一点,下面的类有一个属性“var”,它引用内部变量“uvar”。调用“var”比调用“uvar”要花更长的时间,但是如果开发者和用户都可以只使用“var”而不必跟踪“uvar”,那就太好了。

class MyClass(object):
  def __init__(self):
    self._var = None

  # the property "var". First the getter, then the setter
  @property
  def var(self):
    return self._var
  @var.setter
  def var(self, newValue):
    self._var = newValue
    #... and a lot of other stuff here

  # Use "var" a lot! How to avoid the overhead of the getter and not to call self._var!
  def useAttribute(self):
    for i in xrange(100000):
      self.var == 'something'

对于那些感兴趣的人,在我的电脑上,调用“var”平均需要204纳秒,而调用“uvar”平均需要44纳秒。


Tags: andoftheto函数self属性var
1条回答
网友
1楼 · 发布于 2024-05-14 00:47:26

propertypython文档:https://docs.python.org/2/howto/descriptor.html#properties

class MyClass(object):
    def __init__(self):
        self._var = None

    # only setter
    def var(self, newValue):
        self._var = newValue

    var = property(None, var)


c = MyClass()
c.var = 3
print ('ok')
print (c.var)

输出:

ok
Traceback (most recent call last):
  File "Untitled.py", line 15, in <module>
    print c.var
AttributeError: unreadable attribute

相关问题 更多 >