[Tutor] Why doesn't this work?

Christopher Spears cspears2002 at yahoo.com
Mon Jan 23 21:41:23 CET 2006


I copied this code from Learning Python while learning
about extending types by subclassing:

class Set(list):
	def __init__(self, value=[]):
		list.__init__([])
		self.concat(value)
		
	def intersect(self, other):
		res = []
		for x in self:
			if x in other:
				res.append(x)
		return Set(res)
			
	def union(self, other):
		res = Set(self)
		res.concat(other)
		return res
	
	def concat(self, value):
		for x in value:
			if not x in self:
				self.append(x)
				
def __and__(self, other): return self.intersect(other)
def __or__(self, other): return self.union(other)
def __repr__(self): return 'Set:' +
list.__repr__(self)

if __name__ == '__main__':
	x = Set([1,3,5,7])
	y = Set([2,1,4,5,6])
	print x, y, len(x)
	print x.intersect(y), y.union(x)
	print x & y, x | y
	x.reverse(); print x

Here is the result:
	
cspears at iaws09:/imports/home/cspears/Documents/Python/chap23>
python setsubclass.py
[1, 3, 5, 7] [2, 1, 4, 5, 6] 4
[1, 5] [2, 1, 4, 5, 6, 3, 7]
Traceback (most recent call last):
  File "setsubclass.py", line 32, in ?
    print x & y, x | y
TypeError: unsupported operand type(s) for &: 'Set'
and 'Set'

According to the book, here is what I should get:

Set:[1, 3, 5, 7] Set:[2, 1, 4, 5, 6] 4
Set:[1, 5] Set:[2, 1, 4, 5, 6, 3, 7]
Set:[1, 5] Set:[1, 3, 5, 7, 2, 4, 6]
Set:[7, 5, 3, 1]

Problem 1:  Why isn't "Set:" being printed?  I thought


   def __repr__(self): return 'Set:' +
list.__repr__(self)

would facilitate that.

Problem 2: What is causing the TypeError?

I'm pretty sure I copied this exactly from the book,
so I'm not sure what is not working.


More information about the Tutor mailing list