Object Reference question

Ethan Furman ethan at stoneleaf.us
Tue Sep 1 00:07:02 CEST 2009


josef wrote:
> On Aug 27, 1:35 pm, Ethan Furman <et... at stoneleaf.us> wrote:
> 
>>josef wrote:
>>
>>>Thanks to everyone who responded.
>>
>>>I will be going with some sort of a = MyClass(name = 'a') format. It's
>>>the Python way.
>>
>>>For me, it was very hard to accept that EVERYTHING is an object
>>>reference. And that there are no object reference names, just string
>>>entries in dictionaries. But I think it all makes sense now.
>>
>>>Thanks again,
>>
>>>Josef
>>
>>My apologies if I missed it, but what *exactly* are you planning on
>>doing with your 'name' attribute?  From the posts I've seen so far, I
>>think you are only setting yourself up for failure.
>>
>>~Ethan~
> 
> 
> I'm going to use it for printing purposes. dk = MyClass(name='dk')
> When I need a name dk.name. There will only ever be one dk defined.
> 
> Does that read like I'm setting myself up for failure?

I was hoping someone with more expertise than myself would answer that. 
  :)  Oh well.

The best answer I can give is that you do not want to use 'name' to 
reference the object itself, but only for printing/debugging purposes. 
'name' is just a label for your object, and not necessarily the only 
label;  that particular label may also be lost... Consider:

In [5]: class MyClass(object):
    ...:     def __init__(self, name):
    ...:         self.name = name
    ...:     def __repr__(self):
    ...:         return "MyClass(name='%s')" % self.name
    ...:

In [6]: dk = MyClass(name='dk')

In [7]: dk
Out[7]: MyClass(name='dk')

In [8]: se = dk

In [9]: del dk

In [10]: se
Out[10]: MyClass(name='dk')

In [11]: dk
-------------------------------------------------------------------
NameError                         Traceback (most recent call last)

C:\pythonlib\<ipython console> in <module>()

NameError: name 'dk' is not defined

As you can see, just because you have saved the original name does not 
gaurantee that same name will always reference that same object, or any 
object.

Hope this helps!

~Ethan~



More information about the Python-list mailing list