如何在python中覆盖__str__方法后获取实例的地址

Dob*_*boy 2 python string memory-address

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
Run Code Online (Sandbox Code Playgroud)

有没有办法在覆盖str方法后打印出aFoo的地址?

运用

 >>repr(aFoo) 
Run Code Online (Sandbox Code Playgroud)

解决了我的问题

sen*_*rle 6

至少在cpython中,id提供地址.但输出是十进制的; 你必须将其转换为十六进制:

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

但实际上,覆盖__repr__时函数不会改变__str__.所以你也可以这样做:

>>> class Foo:
...     def __str__(self): return "Foo instance"
... 
>>> a = Foo()
>>> print a
Foo instance
>>> print repr(a)
<__main__.Foo instance at 0x1004d1c68>
Run Code Online (Sandbox Code Playgroud)

id如果您想要的是真的,我认为这是更好的选择id.但id不保证返回地址; 这只是cpython的实现.我不知道是否指定__repr__对象的内置必须返回一个地址,或者它是否必须返回id,或者两者都不返回.因此,如果您特别想要它__repr__提供的任何东西,那么这可能是要走的路.

更新:答案既不是,至少根据语言参考,它只规定__repr__对象的"信息丰富且明确无误".事实上,有时__repr__实际上并没有返回相关特定对象的地址,如下所示:

>>> 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>>'
Run Code Online (Sandbox Code Playgroud)