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

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__)

'>'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值