【问题标题】:using python properties inside __init__?在 __init__ 中使用 python 属性?
【发布时间】:2011-08-06 19:31:57
【问题描述】:

我有一个使用多个 property() 的类。修改文本的字体、大小或字符串等。将需要重新渲染要缓存的表面。

init 中调用类自己的 property() 的推荐方法是什么?问题是变量没有设置,当时我想调用@property DrawText.text

如果我直接设置._text,它会运行:

class DrawText(object):
    """works, Except ignores text.setter"""
    def __init__(self):
        # self.text = "fails" # would fail if here
        self._text = "default"
        self.text = "works"
    @property 
    def text(self):
        '''plain-text string property'''
        return self._text

    @text.setter
    def text(self, text):
        if self._text == text: return       
        self._text = text
        self.dirty = True # .. code re-creates the surface

这也可以运行,并且更接近,但它是否适用于使用不同数据的多个实例?

class DrawText(object):
    """works, Except ignores text.setter"""
    def __init__(self):
        DrawText.text = "default"
        self.text = "works"
    @property 
    def text(self):
        '''plain-text string property'''
        return self._text

    @text.setter
    def text(self, text):
        if self._text == text: return       
        self._text = text
        self.dirty = True # .. code re-creates the surface

【问题讨论】:

    标签: python properties


    【解决方案1】:

    失败是因为在第一次调用 setter 时,支持字段 self._text 尚未定义。

    在类级别上简单地初始化它:

    class DrawText(object):
        _text = None
        # your code here
    

    另一个解决方案(在您的情况下)是简单地手动设置属性的支持字段和脏标志,因为新对象可能被认为是脏的。

    【讨论】:

      【解决方案2】:

      在您的 text 属性中,您可以这样写:

      try:
          return self._text
      except AttributeError:
          self._text = None
      return self._text
      

      那么就不需要在实例化之前(或之上)设置任何内部属性。

      【讨论】:

      • 当属性被频繁读取时,测试 AttributeError 是否会降低性能?
      • 一般来说,如果你认为 try/except 块几乎不会失败,那么它们的成本很低,但如果它们会频繁引发异常,则成本很高。
      • Python 对异常处理没有巨大的性能损失。事实上,这种编程风格实际上是受到鼓励的,请参阅“Easier to Ask Forgiveness than Permission”。当异常实际上经常被抛出时,性能通常会降低,但在你的情况下,它只会被抛出一次,因为那时设置了属性。
      猜你喜欢
      • 2011-12-16
      • 1970-01-01
      • 2011-04-25
      • 2015-11-29
      • 2018-02-23
      • 2013-08-15
      • 2012-02-09
      • 2019-03-02
      • 1970-01-01
      相关资源
      最近更新 更多