Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?
like image 230
Mark Harrison Avatar asked Aug 05 '15 23:08

Mark Harrison


2 Answers

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'
like image 158
Wil Cooley Avatar answered Sep 26 '22 00:09

Wil Cooley


class Foo(object):
    def __repr__(self):
        return '<my stuff, at 0x%x>' % id(self)
like image 37
GP89 Avatar answered Sep 23 '22 00:09

GP89