Skip to content Skip to sidebar Skip to footer

How Do You Obtain The Address Of An Instance After Overriding The __str__ Method In Python

class Bar: pass class Foo: def __str__(self): return 'Foo instance' >> aBar = Bar() >> print aBar <__main__.Bar instance at 0x100572a28> >> aFoo

Solution 1:

At least in cpython, id provides the address. But the output is in decimal; you have to convert that to hex:

>>>f = (x for x in [1,2,3])>>>print f
<generator object <genexpr> at 0x1004d22d0>
>>>'%x' % id(f)
'1004d22d0'

Actually, though, the __repr__ function isn't altered when __str__ is overridden. So you can do this as well:

>>>classFoo:...def__str__(self): return"Foo instance"...>>>a = Foo()>>>print a
Foo instance
>>>printrepr(a)
<__main__.Foo instance at 0x1004d1c68>

I think id is preferable for this, if what you want is really the id. But id is not guaranteed to return the address; that's just the cpython implementation. I don't know whether it's specified that the built-in __repr__ of objects has to return an address, or whether it has to return the id, or neither. So if you specifically want whatever it is that __repr__ provides, then this may be the way to go.

Update: The answer is neither, at least according to the language reference, which dictates only that the __repr__ of an object be "information-rich and unambiguous." And indeed, sometimes the __repr__ does not actually return the address of the specific object in question, as seen here:

>>>a = Foo()>>>'%x' % id(a)
'1004d1fc8'
>>>'%x' % id(a.__str__)
'1004745a0'
>>>'%x' % id(Foo.__str__)
'1004745a0'
>>>repr(a.__str__)
'<bound method Foo.__str__ of <__main__.Foo instance at 0x1004d1fc8>>'

Post a Comment for "How Do You Obtain The Address Of An Instance After Overriding The __str__ Method In Python"