Dispatcher experiment

E

egbert

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.dispatcher as disp

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

def send_food_wish(self):
# started by some event outside this class.
disp.send(signal=self.animal_food, 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_signal = (animal, food)
self.animals[animal] = Animal(animal_food_signal)
disp.connect(self.listen_to_food_wish, signal=animal_food_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.values():
animal.send_food_wish()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top