Alex Martelli wrote:
Bo Peng <[EMAIL PROTECTED]> wrote:
   ...

Thank again for everyone's help. I have learned a lot from the posts,
especially the wrapdict class.


Hmmm, you do realize that wrapdict uses a lot of indirection while my
equivalent approach, just posted, is very direct, right?  To reiterate
the latter, and dress it up nicely too, it's

class wrapwell(object):
    def __init__(self, somedict):
        self.__dict__ = somedict

and use d=wrapwell(whateverdict) to make the wrapper.  Now, reading or
writing d.x is just like reading or writing whateverdict['x'], etc etc.

I was wondering if that would work, but never got around to trying it. It can be used with the property-based auto calculation approach, too (the calculated properties just store the results in self.__dict__ instead of self._data):


class DataManipulator(object):
  def __init__(self, data):
    self.__dict__ = data

  class _utils(object):
    @staticmethod
    def make_prop(name, calculator):
      def get(self, _name=name, _calculator=calculator):
        try:
          return self.__dict__[_name]
        except KeyError:
          val = _calculator(self)
          self.__dict__[_name] = val
          return val
      def set(self, val, _name=name):
        self.__dict__[_name] = val
      def delete(self, _name=name):
        del self.__dict__[_name]
      return property(get, set, delete)

    @staticmethod
    def calc_z(self):
      return self.x + self.y

  z = _utils.make_prop('z', _utils.calc_z)

Py> d = DataManipulator(dict(x=1, y=2))
Py> d.x
1
Py> d.y
2
Py> d.z
3
Py> d.x = 10
Py> d.z
3
Py> del d.z
Py> d.z
12

Cheers,
Nick.

--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---------------------------------------------------------------
            http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to