class Bar:
pass
class Foo:
def __str__(self): return "Foo instance"
>> aBar = Bar()
>> print aBar
<__main__.Bar instance at 0x100572a28>
>> aFoo = Foo()
>> print aFoo
Foo instance
is there a way to print out the address of aFoo after overriding the str method?
using
>>repr(aFoo)
solved my problem
At least in cpython,
idprovides the address. But the output is in decimal; you have to convert that to hex:Actually, though, the
__repr__function isn’t altered when__str__is overridden. So you can do this as well:I think
idis preferable for this, if what you want is really theid. Butidis 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 theid, 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: