pointers

Matthew Scott netnews at goldenspud.com
Sun Dec 28 13:37:11 EST 2003


km wrote:

> Hi all,
> 
> may i know  if  there is any plans of  introducing the concept of pointers
> into python language as in C ?  (atleast in future versions ?)
> 
> regards,
> thanks
> KM

Python is much more "high-level" than C or similar languages.  As such there
is no real need for a concept such as pointers.  Instead, Python uses the
concept of references to connect variable names with the objects they
represent.

For instance, here is an example that demonstrates how two variable names
can "point" (or "refer") to the same object.  The >>> and ... are the
prompts that would be output by the Python interactive interpreter if you
were to run this example code in it.

(After you read this, you might also check out the "Names" and "Assignment"
section of this web page: http://www.effbot.org/zone/python-objects.htm)

Create an empty class that we will add some attributes to below.

>>> class Foo:
...     pass
...

Create an instance of the class.  The name "f1" now refers to the instance
we create.

>>> f1 = Foo()

Add an attribute to the Foo instance we just created.

>>> f1.xyz = 5

Assign the same instance to the name "f2".  Now f1 and f2 are two separate
names, but they both refer to the exact same object.

>>> f2 = f1

Inspect the f2.xyz attribute to see that it contains the same value as
f1.xyz.

>>> f2.xyz
5

Assigning a new value to the f2.xyz attribute results in f1.xyz being
updated as well, because they are the exact same attribute.

>>> f2.xyz = 6
>>> f1.xyz
6

You can use the id() function to show that the names "f1" and "f2" point to
the same object.  (The output of id() will be different on your machine,
since they are internal identification numbers used by Python)

>>> id(f1)
1075959340
>>> id(f2)
1075959340
>>> id(f1) == id(f2)
True

If you want "f2" to be a different object than "f1", assign a new instance
of Foo to the name "f2".  Now "f2.xyz" does not exist since "f2" does not
refer to the same object as "f1" any longer.

>>> f2 = Foo()
>>> f2.xyz
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: Foo instance has no attribute 'xyz'

The ID of two separate objects will always be different.

>>> id(f2)
1075959372
>>> id(f1) == id(f2)
False


-- 
Matthew Scott <netnews at goldenspud.com>





More information about the Python-list mailing list