Pointers

Curtis Jensen cjensen at bioeng.ucsd.edu
Thu Mar 16 18:54:13 EST 2000


Richard Jones wrote:
> 
> [Bjorn Pettersen]
> > d = {'A':[0], 'B':[0]} # use a list as a box to put ints in
> > class A:
> >       def __init__(self):
> >               self.a = d['A']
> > class B:
> >       def __init__(self):
> >               self.b = d['B']
> > a = A()
> > b = B()
> > print a.a[0] # should be 0
> > print b.b[0] # should be 0
> > d['A'][0] = 1
> > d['B'][0] = 2
> > print a.a[0] # should be 1
> > print b.b[0] # should be 2
> 
>    This is an icky solution, but it will work :)
> 
>    A solution that looks more like what Curtis was writing would involve
> intercepting the handling of attributes in the classes 'A' and 'B', like:
> 
> >>> d={'A':0,'B':0}
> >>> class A:
> ...  def __init__(self, d):
> ...   self.d = d
> ...  def __getattr__(self, attr):
> ...   if attr == 'a':
> ...    return d['A']
> ...   return self.__dict__[attr]
> ...
> >>> class B:
> ...  def __init__(self, d):
> ...   self.d = d
> ...  def __getattr__(self, attr):
> ...   if attr == 'b':
> ...    return d['B']
> ...   return self.__dict__[attr]
> ...
> >>> a=A(d)
> >>> print a.a
> 0
> >>> b=B(d)
> >>> print b.b
> 0
> >>> d['A'] = 1
> >>> d['B'] = 2
> >>> print a.a
> 1
> >>> print b.b
> 2
> 
>     So that in this example, we are intercepting the accessing of the
> attributes in the classes 'A' and 'B' so they return the values from the
> dictionary 'd' instead of any attribute 'a' or 'b' they might have.
> 
>     A more complete solution that intercepts the setting of the attributes 'a'
> or 'b' is left as an exercise for the reader.
> 
>        Richard

I need a slightly different twist now.  Somthing like:

>>> d = {'A':0,'B':0}
>>> c = {'A': -> (Pointer to) d['A']}
>>> print c['A']
0
>>> d['A'] = 10
>>> print c['A']
10

-- 
Curtis Jensen
cjensen at be-research.ucsd.edu
http://www-bioeng.ucsd.edu/~cjensen/
FAX (425) 740-1451




More information about the Python-list mailing list