Printing data members of a class
Michael Hudson
mwh21 at cam.ac.uk
Wed Sep 1 19:38:34 EDT 1999
John Fisher <jfisher at are.berkeley.edu> writes:
> Hey folks,
>
> I'm trying to set up a class so that when instances of it are printed, a
> Python prints just a certain data member of the instance. For example:
>
> >>> class x:
> ... data = array([1, 2])
Honk! Honk! You don't actually write it like that do you? You're
setting yourself up for the famous mutable class attribute problem.
[schnipp]
> I've tried playing around with repr, and defining __repr__() in the
> class, but haven't had any luck yet. I'd appreciate any suggestions on
> how to do this.
A point to bear in mind: __repr__ must return a string. Don't do this:
class x:
...
def __repr__(self):
print self.data
do this:
class x:
...
def __repr__(self):
return `self.data`
This trips me up every now and again.
HTH,
Michael
More information about the Python-list
mailing list