我有一个使用几个property()的类.修改文本的字体,大小或字符串等将需要重新渲染表面以进行缓存.
在init中调用类自己的属性()的推荐方法是什么?问题是该变量尚未设置,当时我想调用@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
解决方法:
在您的text属性中,您可以这样写:
try:
return self._text
except AttributeError:
self._text = None
return self._text
然后,在实例化之前(或之前)不需要设置任何内部属性.
标签:python,properties
来源: https://codeday.me/bug/20190626/1296427.html