[Tutor] Get instance name from inside the class ???

Don Arnold Don Arnold" <darnold02@sprynet.com
Thu May 1 22:18:01 2003


----- Original Message -----
From: <pan@uchicago.edu>
To: <tutor@python.org>
Sent: Thursday, May 01, 2003 8:37 PM
Subject: [Tutor] Get instance name from inside the class ???


> Here's another ? for u guys:
>
> class aclass:
>    def __init__(self):
>       self.val = 'avalue'
>
> aaa = aclass()
> bbb = aclass()
>
> Is it possible to put some code inside the aclass to determine
> is it 'aaa' or 'bbb' that this class is bound to ???
>
> pan
>

Not really, because Python variables don't actually have values: they are
object references. So there isn't necessarily a one-to-one relationship
between a variable and the object it points to. For example:

>>> class aclass:
 def __init__(self):
  self.val = 'value'

>>> aaa = aclass()
>>> bbb = aaa
>>> ccc = bbb

These three variables all point to the exact same object:

>>> print aaa
<__main__.aclass instance at 0x00A9E678>
>>> print bbb
<__main__.aclass instance at 0x00A9E678>
>>> print ccc
<__main__.aclass instance at 0x00A9E678>

And modifying one changes all three:

>>> aaa.x = 5
>>> print bbb.x
5
>>> print ccc.x
5

The underlying aclass instance doesn't map to a single variable, so it
doesn't make much sense to consider it bound to one particular variable.

HTH,
Don