class property not working in python 2.5.1

Dan Barbus dan.barbus at gmail.com
Thu Feb 26 02:46:01 EST 2009


Hi,

I have a problem with setting a property to a class instance, in
python 2.5.1. The property is defined through get and set methods, but
when I set it, the setter doesn't get called. Instead, I believe the
property in the instance gets replaced with a new object (string).

I have the following code (stripped down from my program):

class Model():
    def __init__(self, title = ''):
        self._views, self._title = [], None
        self.setTitle(title)

    def addView(self, view):
        self._views.append(view)
        view.onModelUpdated()

    def updateViews(self, trigger = None):
        for view in self._views:
            view.onModelUpdated(trigger)

    def getTitle(self):
        return self._title
    def setTitle(self, t):
        #if self.debug:
        if self._title != t:
            self._title = t
            self.updateViews()
    title = property(fget=getTitle, fset=setTitle)

# client code:

class CountUpdatesView():
    def __init__(self):
        self.updates = 0

    def onModelUpdated(self, trigger):
        self.updates += 1


m = Model('test')
v = CountUpdatesView()
m.addView(v)           # addView calls into v.onModelUpdated() and
                              # v.updates will be 1 after this
m.title = 'new title'    # Model.setTitle calls into v.onModelUpdated
()
                              # and v.updates should become 2
print m._title            # should print 'new title'; instead, prints
'test'

When assigning to m.title, v.updates is not changed, and the last line
prints the original value, passed to the constructor.
Am I missing something?

I noticed that if I put m.setTitle('new title') in the client code,
the code works correctly.



More information about the Python-list mailing list