Using python properties inside __init__?

I have a class using multiple properties (). Change the font, size or line of text, etc. It will require re-rendering of the surface for caching.

What is the recommended way to call the class's own property () inside init ? The problem is that the variable was not set while I want to call @property DrawText.text

If I set ._text directly, it starts:

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 works 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 
+4
source share
2 answers

In the text property you can write this:

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

Then there is no need to set any internal attributes in front of (or in) the instance.

+2
source

This fails because the self._text support self._text is not yet defined when the setter is called for the first time.

Simple class-level initialization:

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

Another solution (in your case) will simply set both the property support field and the dirty flag manually, since the new object is probably considered dirty anyway.

+2
source

All Articles