Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the object name from within the class? [duplicate]

I've got a simple class from which I create two objects. I now want to print the name of the object from within the class. So something like this:

class Example:
    def printSelf(self):
        print self

object1 = Example()
object2 = Example()

object1.printSelf()
object2.printSelf()

I need this to print:

object1
object2

Unfortunately this just prints <myModule.Example instance at 0xb67e77cc>

Does anybody know how I can do this?

like image 581
kramer65 Avatar asked Dec 26 '22 01:12

kramer65


2 Answers

object1 is just an identifier(or variable) pointing to an instance object, objects don't have names.

>>> class A:
...     def foo(self):
...         print self
...         
>>> a = A()
>>> b = a
>>> c = b     
>>> a,b,c    #all of them point to the same instance object
(<__main__.A instance at 0xb61ee8ec>, <__main__.A instance at 0xb61ee8ec>, <__main__.A instance at 0xb61ee8ec>)

a,b,c are simply references that allow us to access a same object, when an object has 0 references it is automatically garbage collected.

A quick hack will be to pass the name when creating the instance:

>>> class A:
...     def __init__(self, name):
...         self.name = name
...         
>>> a = A('a')
>>> a.name
'a'
>>> foo = A('foo')
>>> foo.name
'foo'
>>> bar = foo # additional references to an object will still return the original name
>>> bar.name
'foo'
like image 116
Ashwini Chaudhary Avatar answered Dec 28 '22 14:12

Ashwini Chaudhary


The object does not have a "name". A variable which refers to the object is not a "name" of the object. The object cannot know about any of the variables which refer to it, not least because variables are not a first-class subject of the language.

If you wish to alter the way that object prints, override either __repr__ or __unicode__.

If this is for debugging purposes, use a debugger. That's what it's for.

like image 25
Marcin Avatar answered Dec 28 '22 15:12

Marcin