Mark Harrison
Mark Harrison

Reputation: 304434

Python: how can I get an object's address in the __repr__ method?

How can I get an object's address for inclusion in the object representation, similar to how the default __repr__ works?

>>> a=object()
>>> a
<object object at 0x1002c8090>

class Foo(object):
    def __repr__(self):
        return '<my stuff, at '+obj_address+'>' # how do I get object address?

Upvotes: 7

Views: 7388

Answers (2)

GP89
GP89

Reputation: 6730

class Foo(object):
    def __repr__(self):
        return '<my stuff, at 0x%x>' % id(self)

Upvotes: 6

Wil Cooley
Wil Cooley

Reputation: 940

The address is the ID of the object in hex:

>>> o = object()
>>> repr(o)
'<object object at 0x1028ed080>'
>>> id(o)
4337881216
>>> hex(id(o))
'0x1028ed080'

Upvotes: 14

Related Questions