Puzzling OO design problem
George Sakkis
gsakkis at rutgers.edu
Mon Apr 11 07:08:00 EDT 2005
"Bengt Richter" <bokr at oz.net> wrote in message
news:425919b6.16894062 at news.oz.net...
>
> See if this does what you want:
>
> [snipped]
>
Yes, that's pretty much what I had in mind. I particularly liked the
idea of mirroring automagically the nested class inheritance in each
version. So I tried to refine this recipe a little and I pushed down
the boilerplate code from 3 lines to one word; laziness is a virtue :-)
Below is the test only; I posted the main module to
http://rafb.net/paste/results/Hweu3t19.html to avoid messing up the
indentation.
Cheers,
George
#=================================================
# test.py
from namespace import Namespace
class Era(object):
def __init__(self):
self.lumberjack = self.GameUnit()
self.warrior = self.CombatUnit()
self.shooter = self.RangedUnit()
class MedievalAge(Era):
__metaclass__ = Namespace()
class GameUnit(object):
def move(self): return "MedievalAge.GameUnit.move()"
class CombatUnit(GameUnit):
def fight(self): return "MedievalAge.CombatUnit.fight()"
class RangedUnit(CombatUnit):
def aim(self): return "MedievalAge.RangedUnit.aim()"
class ColonialAge(Era):
__metaclass__ = Namespace(MedievalAge)
class CombatUnit:
def fight(self): return "ColonialAge.CombatUnit.fight()"
class IndustrialAge(Era):
__metaclass__ = Namespace(ColonialAge)
class GameUnit:
def move(self): return "IndustrialAge.GameUnit.move()"
class RangedUnit:
def aim(self): return "IndustrialAge.RangedUnit.aim()"
if __name__ == '__main__':
for era in MedievalAge(), ColonialAge(), IndustrialAge():
for player in era.lumberjack, era.warrior, era.shooter:
for action in "move", "fight", "aim":
try: result = getattr(player,action)()
except AttributeError:
result = "N/A"
print "%s:%s.%s:\t%s" % (type(era).__name__,
type(player).__name__,
action, result)
More information about the Python-list
mailing list