python - python 中重写 __str__ 方法后如何获取实例的地址

标签 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

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

使用

 >>repr(aFoo) 

解决了我的问题

最佳答案

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

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

实际上,__repr____str__ 时,功能不会改变被覆盖。所以你也可以这样做:

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

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

更新:答案都不是,至少根据language reference ,这仅规定 __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>>'

关于python - python 中重写 __str__ 方法后如何获取实例的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6219446/

相关文章:

python - Ubuntu Linux : terminal limits the output when I get the full Twitter Streaming API

python - 将样式对象导出到 csv 时出现 pandas 数据框错误

javascript - jquery:使用字符串作为函数(错误:字符串不是函数)

linux - 来自文件的子字符串

c - C 总是必须使用指针来处理地址吗?

python - 如何使用 matplotlib 绘制多元线性回归模型

android - 尝试从命令行执行脚本时出现 Python 语法错误

javascript - node-red 将 json 字符串解析为 msg.payload

c - 我如何获得这个地址?

c++ - WriteProcessMemory() 返回 487?使用 CheatEngine 找到的值