Michael George Lerner a écrit :
Hi,

As part of my GUI, I have lots of fields that people can fill in,
defined like this:

        self.selection =  Pmw.EntryField(group.interior(),
                                        labelpos='w',
                                        label_text='Selection to use:
',
                                        value='(polymer)',
                                        )

I then use self.selection.get_value() and self.selection.set_value(),
and those two functions are the only ways in which I care about
self.selection. I've never really used properties, getters or setters
before. I tried this, but it didn't work:

def __init__(self):
        self._selection =  Pmw.EntryField(group.interior(),
                                        labelpos='w',
                                        label_text='Selection to use:
',
                                        value='(polymer)',
                                        )
        self.selection = property(self._selection.get_value
(),self._selection.set_value())

What you're passing here are the results of the calls to .get_value and .set_value, not the methods themselves. You'd want:

        self.selection = property(
           self._selection.get_value,
           self._selection.set_value
           )

But as Steven already mentioned, property only works as a class attribute, not as an instance attribute. What you need here is:

class Parrot(object):
  def __init__(self):
self._selection = Pmw.EntryField(...)

  selection = property(
      lambda self: self._selection.get_value(),
      lambda self, value: self._selection.set_value(value)
      )


Of course, I really have ~40 things that I'd like to do this for, not
just one, so I'd like to find a fairly concise syntax.


the property object is just one possible application of the descriptor protocol. You could write your own custom descriptor (warning: untested code, may contains typos etc):

class FieldProperty(object):
    def __init__(self, fieldname):
        self._fieldname = fieldname

    def __get__(self, instance, cls):
        if instance is None:
           # can't work on the class itself
           return self
        return getattr(instance, self._fieldname).get_value()

    def __set__(self, instance, value):
        getattr(instance, self._fieldname).set_value(value)


class Parrot(object):
  def __init__(self):
self._selection = Pmw.EntryField(...)

  selection = FieldProperty("_selection")



HTH
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to