tags:

views:

115

answers:

3

I want to write my own __repr__ for some class that I define. I want it to be similar to the default <__main__.O object at 0x00D229D0>, except have a few other details in there. How do I reproduce that <__main__.O object at 0x00D229D0> thing?

+3  A: 

You can write your own repr like this:

class Test (object):
  def __repr__(self):
    t = type(self)
    return "<Instance of %s.%s at %x>" % (t.__module__, t.__name__, id(self))
kaizer.se
+3  A: 

See http://docs.python.org/reference/datamodel.html#object.%5F%5Frepr%5F%5F

#!/usr/bin/env python
class O(object):
    def __repr__(self):
        return '<%s.%s object at 0x%x>'%(self.__module__,self.__class__.__name__,id(self))
o=O()
print(repr(o))

# <__main__.O object at 0xb7e7d0cc>
unutbu
using `__name__` like that will give false results for subclasses not defined in the same module!
kaizer.se
Thanks for pointing that out. Fixed.
unutbu
A: 
class Base(object):
    pass

class ReprPlus(Base):
    def __init__(self):
        Base.__init__(self)


    def __repr__(self):
        b=Base.__repr__(self)
        print b+" my stuff here" 


r=ReprPlus()
r.__repr__()
jldupont