class Bar:
pass
class Foo:
def __str__(self): return "Foo instance"
>> aBar = Bar()
>> print aBar
>> 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, 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
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:
>>> class Foo:
... def __str__(self): return "Foo instance"
...
>>> a = Foo()
>>> print a
Foo instance
>>> print repr(a)
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__)
'>'