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?
views:
115answers:
3
+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
2009-10-23 12:19:49
+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
2009-10-23 12:21:20
using `__name__` like that will give false results for subclasses not defined in the same module!
kaizer.se
2009-10-23 12:36:57
Thanks for pointing that out. Fixed.
unutbu
2009-10-23 13:59:44
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
2009-10-23 12:22:08