Pointers

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Thu Mar 16 01:21:19 CET 2000


Curtis Jensen wrote in comp.lang.python:
> 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?

Well. The good news is that d['A'] is already a pointer, since it is a
reference. The bad news is that it points to an integer, and integers are
immutable. You can't change the value of 1. d['A']=2 makes the dict point to
another immutable int, it doesn't change a value.

So, if you want 'something close', you *could* use a mutable type instead of
the integers, say, singleton lists:

d = { 'A': [0], 'B': [0] }

class A():
   def __init__(self):
      self.a = d['A']
   
class B():
   def __init__(self):
      self.b = d['B']
	  
a = A()
b = B()

d['A'][0] = 1
d['B'][0] = 2

print a.a[0], b.b[0]

Will print 1 and 2. But it's pretty ugly, and it uses some extra syntax.
Maybe roll your own mutable objects instead of the singleton lists.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
Hi! I'm a .sig virus! Join the fun and copy me into yours!



More information about the Python-list mailing list