python 中重写 __str__ 方法后如何获取实例的地址
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)
解决了我的问题
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
至少在cpython中,
id
提供了地址。但输出是十进制的;您必须将其转换为十六进制:但实际上,当覆盖
__str__
时,__repr__
函数不会改变。所以你也可以这样做:我认为如果你想要的确实是
id
,那么id
更适合这个。但id
不保证返回地址;这只是 cpython 的实现。我不知道是否指定对象的内置__repr__
必须返回地址,或者是否必须返回id
,或者两者都不返回。因此,如果您特别想要 __repr__ 提供的任何内容,那么这可能是正确的选择。更新:答案都不是,至少根据语言参考,仅规定对象的
__repr__
是“信息丰富且明确的”。事实上,有时 __repr__ 实际上并不返回相关特定对象的地址,如下所示:At least in cpython,
id
provides 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
id
is preferable for this, if what you want is really theid
. Butid
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 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: