property collections
gzeljko
gzeljko at sezampro.yu
Tue May 22 09:25:22 EDT 2001
If you insist on this interface:
default = -1
class PC:
def __init__(self):
self.__dict__["index"] = default
def __getitem__(self, item):
self.__dict__["index"] = item
return self
def __getattr__(self, attr):
index = self.index
self.__dict__["index"] = default
if self.__dict__.has_key((index, attr)):
return self.__dict__[(index, attr)]
return self.__dict__[(default, attr)]
def __setattr__(self, attr, value):
index = self.index
self.__dict__["index"] = default
self.__dict__[(index, attr)] = value
gzeljko
----- Original Message -----
From: Robin Becker <robin at jessikat.fsnet.co.uk>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Monday, May 21, 2001 11:48 PM
Subject: Re: property collections
> In article <6qlmnqfsrn.fsf at abnoba.intevation.de>, Bernhard Herzog
> <bh at intevation.de> writes
> >Robin Becker <robin at jessikat.fsnet.co.uk> writes:
> ...
>
>
> This looks more interesting. The problem for me is that the actual items
> are of a particular PropertyHolder class, but I think it's possible to
> create these on the fly.
>
> Thanks for the code.
>
> >This seems to work without cyclic references:
> >
> >class ItemProxy:
> >
> > def __init__(self, parent, index):
> > self.__dict__["_parent"] = parent
> > self.__dict__["_index"] = index
> >
> > def __getattr__(self, attr):
> > return self._parent.get_attribute(self._index, attr)
> >
> > def __setattr__(self, attr, value):
> > self._parent.set_attribute(self._index, attr, value)
> >
> >class Parent:
> >
> > def __init__(self):
> > self.items = {}
> >
> > def __getitem__(self, index):
> > return ItemProxy(self, index)
> >
> > def set_attribute(self, index, attr, value):
> > item = self.items.get(index)
> > if item is None:
> > item = self.items[index] = {}
> > item[attr] = value
> >
> > def get_attribute(self, index, attr):
> > item = self.items.get(index)
> > if item is not None and item.has_key(attr):
> > return item[attr]
> > return getattr(self, attr)
> >
> >
> >Sample session:
> >
> >$ python1.5 -i itemproxy.py
> >>>> p = Parent()
> >>>> p.a = 1
> >>>> p.b = 2
> >>>> p[1].a = 0.5
> >>>> p[1].a
> >0.5
> >>>> p[1].b
> >2
> >>>> p[2].a
> >1
> >>>> p[2].b
> >2
> >>>>
> >
> >
> >The trick here is that the parent does not have any references to the
> >objects returned by the __getitem__ method, so there are no cyclic
> >references.
> >
> >
>
> --
> Robin Becker
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list