When is it a pointer (aka reference) - when is it a copy?

Laszlo Nagy gandalf at designaproduct.biz
Wed Sep 13 13:29:32 EDT 2006


John Henry írta:
> Hi list,
>
> Just to make sure I understand this.
>
> Since there is no "pointer" type in Python, I like to know how I do
> that.
>
> For instance, if I do:
>
>    ...some_huge_list is a huge list...
>    some_huge_list[0]=1
>    aref = some_huge_list
>    aref[0]=0
>    print some_huge_list[0]
>
> we know that the answere will be 0.  In this case, aref is really a
> reference.
>
> But what if the right hand side is a simple variable (say an int)?  Can
> I "reference" it somehow?  Should I assume that:
>
>    aref = _any_type_other_than_simple_one
>
> be a reference, and not a copy?
>   
The short answer is that you need to keep the immutable value inside a 
mutable object.

The long answer:

a.) You can reference the immutable object just like any object, but you 
cannot change the immutable object. For instance, when you do

a = 1
a += 2

then you are rebinding the variable 'a' to a different object (namely, 
the 2 int object.)

b.) You can however, keep a reference to your current immutable object 
inside a mutable object. In many cases, the mutable object will be a 
namespace dictionary.

A module is a very simple example:

a = 1
def f1():
    global a
    a += 1

def f2():
    global a
    a += 10

f1()
f2()
print a # prints 12

Notice that the "a+=10" will actually rebind the variable to a different 
object.

In other cases, you will be using an object or a class:

class A(object):
    a = 5

def inc_id(obj):
    obj.id += 1

a = A() # a.id is 5 here
a.id = 4 # makes a.id a reference to 4
inc_id(a) # makes a.id a reference to 5 again


Best,

  Laszlo




More information about the Python-list mailing list