Reputation: 7511
I have a class using several property()'s. Modifying a text's font, size, or string, etc.. will require a re-render of a surface to cache.
What is the recommended way to call a class's own property(), inside init ? The problem is that the variable has not been set, at the time I want to call @property DrawText.text
If I directly set ._text, it runs:
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
This also runs, and is closer, but will it work with multiple instances, using different data?
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
Upvotes: 4
Views: 2030
Reputation: 4367
In your text property, you could write this:
try:
return self._text
except AttributeError:
self._text = None
return self._text
Then there is no need to set any internal attributes before (or on) instantiation.
Upvotes: 2
Reputation: 318518
It fails because the backing field self._text
is not defined yet when the setter is called the first time.
Simple initialize it on the class level:
class DrawText(object):
_text = None
# your code here
Another solution (in your case) would be simply setting both the backing field of the property and the dirty flag manually since a new object is probably considered dirty anyway.
Upvotes: 2