[Tutor] the class struggle
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:
"Ways we might define children's behavior()"
return "Go away!"
Spawn instances with different ideas about
behavior() depending on arg 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")