相关疑难解决方法(0)

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

在python类中,@ property是一个很好的装饰器,可以避免使用显式的setter和getter函数.然而,它的成本是"经典"类功能的2-5倍.在我的情况下,在设置属性的情况下这是非常好的,与设置时需要完成的处理相比,开销是微不足道的.

但是,在获得房产时我不需要处理.它总是只是"回归自我.属性".是否有一种优雅的方式来使用setter但不使用getter,而不需要使用不同的内部变量?

为了说明,下面的类具有属性"var",它指的是内部变量"_var".它需要更长的时间称为"VAR"比"_var"但它会是很好,如果开发者和用户都可以只使用"无功",而无需守得的"_var"的轨道.

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'
Run Code Online (Sandbox Code Playgroud)

对于那些感兴趣的人,在我的电脑上调用"var"平均需要204 ns,而调用"_var"平均需要44 ns.

python properties class timing

49
推荐指数
3
解决办法
2万
查看次数

标签 统计

class ×1

properties ×1

python ×1

timing ×1