python references

Rob Wolfe rw at smsnet.pl
Mon Feb 5 06:52:30 EST 2007


dustin.getz at gmail.com wrote:
> >>> from Numeric import zeros
> >>> p=zeros(3)
> >>> p
> array([0,0,0])
> >>> p[0]
> 0
> >>> x=p[0]

`x' is now a reference to immutable integer object
with value 0, not to first element of array `p'

> >>> x=10

now `x' is a reference to immutable integer object
with value 10, array doesn't change

> >>> p
> array([0,0,0]) #actual behavior
> #array([10,0,0]) #desired behavior
>
> I want x to be a C++-esque reference to p[0] for convenience in a
> vector3 class.  i dont want accessor methods.  i know python can do
> this, but it's been a long time since I used it and am unsuccessful in
> my googling and docreading.  a little help please?

You can have such a reference to mutable objects.
Consider this:

>>> p = [[0,0,0], [0,0,0]]
>>> x = p[0]        # reference to mutable list object
>>> x[0] = 10
>>> p
[[10, 0, 0], [0, 0, 0]]

--
HTH,
Rob




More information about the Python-list mailing list