Pointers

Bjorn Pettersen bjorn at roguewave.com
Wed Mar 15 19:28:31 EST 2000


Curtis Jensen wrote:
> 
> Richard Jones wrote:
> >
> > [Curtis Jensen]
> > > Pointers are sometimes usefull.  I have a module that creates a
> > > dictionary.  I want to include some elements from the distionary in one
> > > class and other elements in another class.  If I had pointers, I could
> > > do that.  Is there another way?
> >
> >    As I explained in my response to your post (unlike the unhelpful Bjorn ;)
> > you're already dealing with a reference there. The dictionary is an object and
> > your only control over it is via your reference to it. You can make labels
> > (variables) for that reference, or pass that reference around to functions or
> > methods. I think you'll find that you can already do what you want:
> >
> > >>> class A:
> > ...  def foo(self, a):
> > ...   a['A'] = 1
> > ...
> > >>> class B:
> > ...  def foo(self, b):
> > ...   b['B'] = 1
> > ...
> > >>> a=A()
> > >>> b=B()
> > >>> d={}
> > >>> a.foo(d)
> > >>> b.foo(d)
> > >>> d
> > {'B': 1, 'A': 1}
> >
> >         Richard
> 
> Maybe I'm missunderstanding, but it appears that this is just a copy
> routine.  I want something like this:
> 
> >>> d={'A':0,'B':0}
> >>> class A:
> ...   def __init__(self):
> ...     self.a -> (Pointer to) d['A']
> ...
> >>> class B:
> ...   def __init__(self):
> ...     self.b -> (Pointer to) d['B']
> >>> a=A()
> >>> b=B()
> >>> print a.a
> 0
> >>> print b.b
> 0
> >>> d['A'] = 1
> >>> d['B'] = 2
> >>> print a.a
> 1
> >>> print b.b
> 2
> 
> If the data in the dictionary changes, I want the data in the class to
> automaticaly change also.  Is this possible?  Or at least something
> close?

yes. If you read through what Richard wrote above a couple of times,
while remembering that ints are immutable and lists aren't, you should
be able to understand the following:

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

Please don't do this <wink>  There is almost always a more
straightforward way of doing things like this.

-- bjorn

ps: in Richard's example the dictionary is _not_ passed by value, so
there is no copying going on. The technical term is
pass-by-object-reference, but you can think of it as pass-by-pointer in
e.g. C++/C but with automatic dereferencing.




More information about the Python-list mailing list