Dispatcher experiment

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • egbert

    #1

    Dispatcher experiment

    As an exercise in the use of dispatcher
    I concocted a Zoo with some Animals, see below.
    It works, but I think it is convoluted, obfuscated.

    The idea is that in the Zoo each animal needs its own type of food,
    and the Zoo should acknowledge a wish for that food,
    as soon as the animal says it wants food.
    The number and kind of animals (and their food) may vary.

    The general problem is that you may have an unspecified number
    of instances of some type, and that each instance must be recognized
    and handled by the specific signal it sends into the world.

    I would appeciate any comments or improvements on my design.
    In a python shell you may test it with:
    import dip
    zoo = dip.Zoo()
    zoo.animals["fish"].send_food_wish ()

    egbert

    #!/usr/bin/env python
    # dip.py := experiment with Patrick O'Brien's dispatcher

    import wx.py.dispatche r as disp

    class Animal(object):
    def __init__(self, animal_food):
    self.animal_foo d = animal_food

    def send_food_wish( self):
    # started by some event outside this class.
    disp.send(signa l=self.animal_f ood, sender=self)

    class Zoo(object):
    def __init__(self):
    # dummies for some gui that accepts names of animals and their food:
    animal_list = ["bird", "lion", "fish"]
    food_list = ["bread", "meat", "plankton"]

    # zoo administration: register animals and their food;
    self.animals = {}
    for animal,food in zip(animal_list , food_list):
    animal_food_sig nal = (animal, food)
    self.animals[animal] = Animal(animal_f ood_signal)
    disp.connect(se lf.listen_to_fo od_wish, signal=animal_f ood_signal)

    def listen_to_food_ wish(self, signal, sender=disp.Any ):
    print "sender %s is %s and wishes to eat %s now" % \
    (sender, signal[0], signal[1])

    if __name__ == '__main__':
    zoo = Zoo()
    for animal in zoo.animals.val ues():
    animal.send_foo d_wish()
    --
    Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
    =============== =============== =============== =============== ============
Working...