[Tutor] Re: Classes!Classes!Classes!

Skip Montanaro skip@mojam.com (Skip Montanaro)
Thu, 23 Dec 1999 12:01:56 -0600 (CST)


    CG> Can classes be composed of other (sub)classes?
    CG> Can classes be composed of multiple copies of the same (sub)class?

In a manner of speaking.  What you're asking about is generally called
aggregation.  The technique you'd normally use in Python (as Chris Tismer
pointed out) would be to define one or more instance attributes that
reference different pieces of the aggregate.  Depending how you want to
structure things you might have something simple (one instance attribute,
rooms) like

    class Room:
	def __init__(self, width, length, height=8):
	    self.width = width
	    self.length = length
	    self.height = height

	def dimensions(self):
	    return (self.width, self.length, self.height)

    class House:
	def __init__(self):
	    self.rooms = []

	def addroom(self, room):
	    self.rooms.append(room)

	def dimensions(self):
	    dims = []
	    for r in self.rooms:
		dims.append((r.__class__.__name__, r.dimensions()))
	    return dims

	def getRoomsOfType(self, cls):
	    rooms = []
	    for r in self.rooms:
		if r.__class__ == cls:
		    rooms.append(r)
	    return rooms

    class LivingRoom(Room): pass ;
    class BedRoom(Room): pass ;
    class BathRoom(Room): pass ;
    class Kitchen(Room): pass ;
    class Garage(Room): pass ;

    house = House()
    house.addroom(LivingRoom(20,20))
    house.addroom(BedRoom(15,15))
    house.addroom(BedRoom(10,10))
    house.addroom(BedRoom(12,13))
    house.addroom(BathRoom(6,8))
    house.addroom(BathRoom(10,10))
    house.addroom(Kitchen(9,15))
    house.addroom(Garage(22,22,10))
    print house.dimensions()
    print house.getRoomsOfType(BedRoom)

(which most Americans will recognize as the standard 3-bedroom, 2-bath ranch
style home. ;-)

You can, of course, get more complex defining individual instance attributes
for each of the different types of rooms.

The House.dimensions method demonstrates one way to delegate a method call
to the aggregate object (the house) to a collection of subobjects (in this
case, the rooms).  The House.getRoomsOfType method demonstrates one way to
select those rooms of a particular type.

Skip Montanaro | http://www.mojam.com/
skip@mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...