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?
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With