Finding the instance reference of an object

Joe Strout joe at strout.net
Thu Oct 16 19:24:28 CEST 2008


On Oct 16, 2008, at 10:59 AM, Larry Bates wrote:

>> how do i find that the name is 'bob'
>
> Short answer is that you can't.  This because Python's names (bob)  
> are bound to objects (modulename.objectname()).  They are NOT  
> variables as they are in "other" programming languages.

Which other programming languages?  I've never seen an OOP language  
that didn't work the same way as Python.

However, 'bob' here really is a variable.  It's a variable whose value  
(at the moment) is a reference to some object.

> It is perfectly legal in Python to bind multiple names to a single  
> object:
>
> a=b=c=modulename.objectname()

Right -- three variables (a, b, and c) that all have the same value,  
i.e. all refer to the same object.  There's nothing more mysterious  
here than

i=j=k=42

where i, j, and k all have the same value.  (The OP's question would  
be like asking "what is the name of the variable referring to 42?  And  
while you might, in theory, be able to produce a list of all such  
variables by trolling through the Python's internals, it's a bit of a  
silly thing to do.)

> a, b, and c all point to the same object.  An object can have an  
> unlimited number of names bound to it.  This is one of the most  
> difficult concepts for many beginning Python programmers to  
> understand (I know I had a difficult time at first).  It is just not  
> how we taught ourselves to think about "variables" and you can write  
> quite a lot of Python treating the names you bind to objects like  
> they were "variables".

Well, they are variables.  I'm not quite grasping the difficulty  
here... unless perhaps you were (at first) thinking of the variables  
as holding the object values, rather than the object references.  That  
is indeed something important to grasp, since it explains why if you do

  a = b   # where b was some object with an attribute 'foo'...
  a.foo = 42

...you now find that b.foo is 42 too.  Nothing mysterious once you  
realize that the value of a and b is a reference to some object that  
has a "foo" attribute.

Not sure if all this was helpful to anyone, but I hope so!

Best,
- Joe




More information about the Python-list mailing list