Printing data members of a class

Robert Kern kernr at mail.ncifcrf.gov
Wed Sep 1 18:28:19 EDT 1999


On Wed, 01 Sep 1999 21:39:53 GMT, John Fisher
<jfisher at are.berkeley.edu> wrote:

>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])
>
>>>> y = x()
>>>> y
>[1 2]
>
>or at least
>>>> print y
>[1 2]
>
>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.

from Numeric import *
# That is what you're using, right?

class x:
    data = array([1, 2])

    def __str__(self):
        return str(self.data)

    __repr__ = __str__  
    # If you must; it would be better to have __repr__ return a string
    # that could be meaningfully eval'ed, but if you need the
    # behaviour in your first example, this is how to do it.

>Thanks!
>
>John

Robert Kern           |
----------------------|"In the fields of Hell where the grass grows high
This space            | Are the graves of dreams allowed to die."
intentionally         |           - Richard Harter
left blank.           |




More information about the Python-list mailing list