Pointers

Bjorn Pettersen bjorn at roguewave.com
Thu Mar 16 19:21:37 EST 2000


Curtis Jensen wrote:
> 
> 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
> 

How about...:

class ptr: pass

x = ptr()
x.value = 0
y = ptr()
y.value = 0
d = {'A':x,'B':y}
c = {'A':d['A']}
print c['A'].value
d['A'].value = 10
print c['A'].value

You could even think of .value as a dereferencing operator...

not-condoning-any-of-this'ly y'rs
-- bjorn




More information about the Python-list mailing list