class property not working in python 2.5.1

D

Dan Barbus

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.
 
U

utnapistim

Dan said:
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)

*snip*

Properties don't work correctly on old style classes. You have to
subclass from object in order to get a new style class.

class Model(object):
    pass

Christian

Thanks, that solved the problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top