[Tutor] is it possible to call a setter property during class instantiation?

Evert Rol evert.rol at gmail.com
Thu Aug 12 18:37:15 CEST 2010


> Does anyone know if it's possible to call a property setter inside of a class's init method?  Below is a code sample of what I'm trying to do. 

Just a quick guess:


> class Question(object);

replace the semi-colon with a colon (I assume it's just a typo, since you don't get an error for this).

> 
>     def __init__(self, value):
>         self.text(value)

	self.text = value  # is the way to do this, if you're using it as a property.


>     
>     @property
>     def text(self):
>         return self._text
> 
>     @text.setter
>     def text(self, value):
>         if not isinstance(value, str):
>             raise TypeError
>         self._text = value
> 
> 
> Here's an explanation of what I'm trying to accomplish:
> 
> I have a class with an init method that is getting bloated with error-checking guard clauses. I was hoping to "hide" some of these guard clauses by using the @property decorator and its associated setter method. I'd like to use the Question.text property to set the value (or raise an error) upon instantiation of a Question object. I figured this would clean up my init method and move the error-checking code closer to the relevant class attribute. I've tried numerous variations on the above init method, but all without success.
> 
> 
> In the current version, when I try:
> 
> >>> q = Question("Hello world?") 
> 
> I get the following error:
> 
> AttributeError: 'Question' object has no attribute '_text'
> 
> I was hoping text property would create self._text for me on instantiation, but apparently no dice. I'm also getting errors when I do the below variations:
> 
> ### variation 1 ####
> def __init__(self, value):
>     self._text = ''
>     self.text(value)
> 
> ### variation 2 ####
> def __init__(self, value):
>     self._text = None
>     self.text(value)
> 
> Can anyone point out what I'm doing wrong? I suspect I'm misunderstanding properties and/or the finer points of object instantiation. Any help would be greatly appreciated! 

Again, see the correction above: use 'self.text = value'. Don't use self._text, nor call self.text()

> 
> Thanks!
> Serdar



More information about the Tutor mailing list