Can I reference 1 instance of an object by more names ? rephrase

Carsten Haese carsten at uniqsys.com
Wed May 23 08:07:18 EDT 2007


On Wed, 2007-05-23 at 12:55 +0200, stef wrote:
> Is there another way, without using the dummy index, to achieve the same 
> results ?
> 
> thanks,
> Stef Mientki
> 
> <Python>
> class cpu_ports(object):
>     def __init__(self, value=0):
>         self._d = value
>     def __setitem__(self, index, value):
>       print 'vv'
>       self._d = value
>     def __getitem__(self, index):
>       return self._d
>     def __repr__(self):
>       return str(self._d)
> 
> name1 = cpu_ports()     # create an instance
> name2 = name1            # refer with a second name to the same instance
> print name1, name2      # test ok
> 
> name1[0] = 25               # assign a value to the instance
> print name1, name2      # both references are OK
> 
> name2[0] = 26               # assign another value through the other name
> print name1, name2      # both reference are OK
> 
> name2[0] = name1[0] + 13  # use both names at either side of an assignment
> print name1, name2            # both references still OK
> </Python>

An assignment without a dummy index or attribute, i.e. a "plain"
assignment to name1 or name2, will never do what you want, for two
reasons:

1) Assignments modify namespaces, not objects.
2) Assignments can not be overridden.

The reason why the code with dummy indexes works is that those are not
actually namespace-modifying assignments; they are shorthand notations
for __setitem__ method calls. You could achieve the same effect by using
an attribute instead:

>>> class A(object): pass
... 
>>> name1 = A()
>>> name2 = name1
>>> name1.value = 25
>>> print name1.value, name2.value
25 25
>>> name2.value = 26
>>> print name1.value, name2.value
26 26
>>> name2.value = name1.value + 13
>>> print name1.value, name2.value
39 39

The first statement modifies the namespace by binding the name "name1"
to a newly created instance of class A. The second statement modifies
the namespace by binding the name "name2" to the very same instance.
Until either name1 or name2 are reassigned, the object known as name1 is
now *identical* to the object known as name2. Not equal, not
indistinguishable, but identical. name1 and name2 are two different
names for the same thing.

None of the statements that follow are assignments. They are disguised
__setattr__ method calls on that one object that is known by two names.
Those calls will modify that object (not the namespace), and any changes
made to the object known as name1 are immediately visible in the object
known as name2, because it's the same object.

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list