# Pointers

Richard Jones Richard.Jones at fulcrum.com.au
Thu Mar 16 01:37:21 CET 2000

```[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

```