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

Serdar Tumgoren zstumgoren at gmail.com
Thu Aug 12 18:20:48 CEST 2010

Hey all,

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.

class Question(object);

    def __init__(self, value):

    def text(self):
        return self._text

    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

### variation 1 ####
def __init__(self, value):
    self._text = ''

### variation 2 ####
def __init__(self, value):
    self._text = None

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!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100812/909798ac/attachment.html>

More information about the Tutor mailing list