how do you obtain the address of an instance after

2019-07-10 11:15发布

问题:

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

回答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:

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