Object Reference question
Miles Kaufmann
milesck at umich.edu
Fri Aug 21 02:34:13 EDT 2009
On Aug 20, 2009, at 11:07 PM, josef wrote:
> To begin, I'm new with python. I've read a few discussions about
> object references and I think I understand them.
>
> To be clear, Python uses a "Pass By Object Reference" model.
> x = 1
> x becomes the object reference, while an object is created with the
> type 'int', value 1, and identifier (id(x)). Doing this with a class,
> x = myclass(), does the same thing, but with more or less object
> attributes. Every object has a type and an identifier (id()),
> according to the Python Language Reference for 2.6.2 section 3.1.
>
> x in both cases is the object reference. I would like to use the
> object to refer to the object reference.
Stop right there. 'x' is not *the* object reference. It is *an*
object reference (or in my preferred terminology, a label). Suppose
you do:
x = myclass()
y = x
The labels 'x' and 'y' both refer to the same object with equal
precedence. There is no mapping from object back to label; it is a
one-way pointer. Also importantly, labels themselves are not objects,
and cannot be accessed or referred to.
(This is a slight oversimplification; thanks to Python's reflection
and introspection capabilities, it is possible to access labels to
some extent, and in some limited situations it is possible to use
stack inspection to obtain a label for an object. But this is hackish
and error-prone, and should never be used when a more Pythonic method
is available.)
> The following is what I would like to do:
> I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d
> is an object reference. Entering dk gives me the object: [MyClass0
> instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at
> 0x0010 ... ]
>
> I need the object reference name (a,b,c,d) from dk to use as input for
> a file.
It sounds like you should either be storing that name as an attribute
of the object, or using a dictionary ({'a': a, 'b': b, ...}).
-Miles
More information about the Python-list
mailing list