Simulating call of instance like a list or tuple
Jason Orendorff
jason at jorendorff.com
Sun Jan 13 12:56:55 EST 2002
> It seems everyone is thinking that I want __repr__ or __str__, which is in
> the right vein, but not quite it. I want the same functionality, but I
> want to be able to return something other than a string. I don't think it
> exists outside of the built-in classes.
All the built-in types use __repr__ to do this, and they
all return strings.
Your __repr__ method should figure out the value you want to print,
then convert it to a string.
class MyClass:
def __repr__(self):
# Here's the data I want to display...
data = self.my_data
# Now convert it to a string and return that.
return repr(data)
>>> x = MyClass()
>>> x.my_data = (3, 4, 'Poughkeepsie', 2.71828, u'\N{DAGGER}\N{BULLET}')
>>> x
(3, 4, 'Poughkeepsie', 2.71828, u'\u2020\u2022')
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list