Looking for assignement operator

Bruno Desthuilliers onurb at xiludom.gro
Tue Oct 17 18:44:51 CEST 2006

Jerry wrote:
>> class MyClass:Descriptors don't work fine with old-style classes.
> Interesting, I have used this construct before in Python 2.4.3 and not
> run into the recursion problem you talk about.

The recursion problem doesn't occur with you original code (for the good
reason that there's a name error way before). It doesn't even occur when
the cause of the name error is corrected, since the first (explicit)
call to setval() in the __init__ rebind self._val to the value passed -
so the property is in fact *never* used.

> Also, it has worked
> fine for me.  

For a very peculiar definition of "works fine" !-)

> Perhaps you can post a link to your source

class MyClass:
    def __init__(self, val):
        print "in __init__, after setval(): self._val is %s" \
               % type(self._val)

    def getval(self):
        print "in getval - you won't see me unless you explicitely call
        return self._val

    def setval(self, val):
        print "in setval"
        self._val = val
        print "you wont see me no more unless you explicitely call setval"

    _val = property(getval, setval)

> so that I
> could study it and understand what circumstances my solution works

It doesn't work in any circumstances.

> and
> what the recommended construct actually is.

class MyWorkingClass(object):
    def __init__(self, val):
        self.val = val

    def _setval(self, val):
        print "_setval to %s" % val
        self._val = val

    def _getval(self):
        print "_getval"
        return self._val

    val = property(_getval, _setval)

>> May I kindly suggest that you learn more about properties and test your
>> code before posting ?-)
> I did test this on Python 2.4.3 in Mac OS X 10.4 and it worked fine.

Here's the exact code you posted:

class MyClass:
    def __init__(self, val):

    def getval(self):
        return self._val

    def setval(self, val):
        assert(isinstance(val, int))
        self._val = val

    _val = property(self.getval, self.setval)

And here's the result:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/tmp/python-30955cPK.py", line 1, in ?
    class MyClass:
  File "/usr/tmp/python-30955cPK.py", line 15, in MyClass
    _val = property(self.getval, self.setval)
NameError: name 'self' is not defined

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list