[Tutor] the class struggle

Kirby Urner urnerk@qwest.net
Fri, 30 Nov 2001 16:35:43 -0800

Hi Rob --

It occurred to me later that maybe what you were trying
to do was write a factory class that'd spawn instances
which had different behaviors depending on the name used
to instance them (as an arg to __init__).

It'd be like a computer game, where your factory produces
game characters, and if you pass it 'King' (as a name),
then the instantiated character should do something
different when you go myking.says(), then if you
instantiate using the name 'Peasant' and go myguy.says().

Anyway, even if that's not what you meant, the code below
might provide useful grist for the mill anyway.  I stick
possible behaviors in a Behaviors class, and then use the
Factory class (which inherits from Behavior) to assign
different Behavior methods to self.behavior:

   class Behaviors:
        "Ways we might define children's behavior()"
	def namer(self):
	    return self.name
	def rand(self):
	    return randint(1,10)
	def deter(self):
	    return "Go away!"
   class Factory(Behaviors):
        Spawn instances with different ideas about
        behavior() depending on arg name
	def __init__(self,name):
	    self.name = name
	    if name == "Boring":
		self.behavior = self.namer
	    elif name == "Randomizer":
		self.behavior = self.rand
		self.behavior = self.deter

  >>> obj1 = Factory("Boring")
  >>> obj2 = Factory("Randomizer")
  >>> obj3 = Factory("Anybody")
  >>> obj1.behavior()
  >>> obj2.behavior()
  >>> obj3.behavior()
  'Go away!'