Determining names of instances

Pat Knight nospam at ktgroup.co.uk
Tue Jan 16 04:39:57 EST 2001


"Daniel Klein" <DanielK at jBASE.com> writes:

> A question I hope has a simple answer. Take the following simple class and
> instance
> 
>     class foobar:
>         pass
> 
>     foo = foobar()
> 
> The question is, is there a way for the object 'foo' to know that its name
> is 'foo'?

There isn't, because the variable 'foo' isn't an instance of the foobar class.
Instead, foo is a reference to said instance. The statement
        bar = foo
creates a new reference to the same object. It does not copy the object as
might happen in C++.

This should let you see why the object doesn't have the name 'foo'. Is it 'foo'
or 'bar' or both after the assignment?

If you really need to have the instance know it's own identity, pass a value
into a parameter at construction time e.g.
        class foobar:
            def __init__ (self, my_id):
                self.my_id = my_id

        foo = foobar('foo')

However, please ask why the object needs to know it's own identity. Is it so
that it can manipulate a particular external object? Have it contain a
reference to that object. Is it for program trace or debug logging? Use
id(self) to get an id that is independent of the name referring to the object.




More information about the Python-list mailing list