Object Reference question

Simon Forman sajmikins at gmail.com
Fri Aug 21 13:54:13 EDT 2009


On Aug 21, 12:12 pm, josef <jos... at gmail.com> wrote:
> > > I need the object reference name (a,b,c,d) from dk to use as input for
> > > a file.
>
> > You'll have to track that yourself.
>
> I'm a bit shocked that there isn't a method for catching object
> reference names. I think that something like a = MyClass0(name =
> 'a', ...) is a bit redundant. Are definitions treated the same way?
> How would one print or pass function names?

There's no such thing as "object reference names".  Object references
do not have names.

When you run a piece of code like "a = object()" a string "a" is used
as a key in a dictionary and the value is the "object reference".

Consider:

[None][0] = object()

(Create an anonymous list object with one item in it and immediately
replace that item with an anonymous object instance.)

There's no name to catch.

Objects know nothing about their "enclosing" namespace. So if you want
them to have names you have to explicitly give them name attributes.
(However, this won't affect their enclosing namespaces.)

As Bruno said, think of "foo = something" as shorthand for
"some_namespace_dictionary['foo'] = something".


The two exceptions to this are 'def' and 'class' statements which both
create name->object (key, value) pairs in their current namespace AND
give the objects they create '__name__' attributes (pretty much just
as an aid to debugging.)

In [1]: def foo(): pass
   ...:

In [2]: foo.__name__
Out[2]: 'foo'

In [3]: class foo(): pass
   ...:

In [4]: foo.__name__
Out[4]: 'foo'


> > A good way to keep track of name-to-object mappings is with Python's
> > built-in mapping type, ‘dict’::
>
> >     dk = {'a': a, 'b': b, 'c': c, 'd': d}
>
> > (There are more efficient ways to create a dictionary without such
> > repetition, of course, but this is more illustrative of the point.)
>
> > You can then get a list (assembled in arbitrary sequence) of just the
> > keys, or just the values, or the key-value pairs, from the dict with its
> > ‘keys’, ‘values’, and ‘items’ methods respectively::
>
> >     >>> dk = {'a': a, 'b': b, 'c': c, 'd': d}
> >     >>> dk.keys()
> >     ['a', 'c', 'd', 'b']
> >     >>> dk.values()
> >     [<MyClass instance at 0x3462>, <MyClass instance at 0x2983>, <MyClass instance at 0x3717>, <MyClass instance at 0x3384>]
> >     >>> dk.items()
> >     [('b', <MyClass instance at 0x2983>), ('c', <MyClass instance at 0x3462>), ('a',  <MyClass instance at 0x3384>), ('d',  <MyClass instance at 0x3717>)]
>
> > Each of these is even better used as the iterable for a ‘for’ loop::
>
> >     >>> for (key, value) in dk.items():
> >     ...     print "Here is item named", key
> >     ...     print value
>
> I think I'll just add a 'name' to the classes' init defintion.

That's the way to do it. :]




More information about the Python-list mailing list