Printing data members of a class

Hans Nowak ivnowa at hvision.nl
Thu Sep 2 09:49:33 EDT 1999


On 1 Sep 99, John Fisher 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])

What's this?

(trying to duplicate it)

>>> from array import array
>>> data = array([1,2])
Traceback (innermost last):
  File "<pyshell#1>", line 1, in ?
    data = array([1,2])
TypeError: argument 1: expected char, int found
>>> 

...Maybe you just meant a list? Or maybe this is an array type I 
don't know (maybe in Numeric)? ...Anyway,

> 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.

__repr__ has been covered in the newsgroup lately, so you should be 
able to find more on that by poking around a bit in DejaNews. 
Meanwhile, try the following:

>>> class x:
	def __init__(self):
		self.data = [1,2]
	def __repr__(self):
		return `self.data`
		
>>> y = x()
>>> y
[1, 2]
>>> 

This should do the trick.

Hans Nowak (ivnowa at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
Snippets: http://www.hvision.nl/~ivnowa/snippets/




More information about the Python-list mailing list